Skip to content

Commit

Permalink
Merge pull request #306 from sontixyou/fix-has_many-method
Browse files Browse the repository at this point in the history
Fix arguments of has_many method
  • Loading branch information
flavorjones authored May 3, 2024
2 parents 0d5ec8a + adece84 commit da9eeee
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/associations/associations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def self.extended(base)
require_relative 'reflection_extensions'
end

def has_many(association_id, **options)
def has_many(association_id, scope = nil, **options, &extension)
if options[:through]
klass_name = association_id.to_s.classify
klass =
Expand Down
42 changes: 42 additions & 0 deletions spec/associations/active_record_extensions_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,32 @@ def define_book_classes
end
end

def define_person_classes
define_ephemeral_class(:Country, ActiveHash::Base) do
self.data = [
{:id => 1, :name => "Japan"}
]
end

define_ephemeral_class(:Person, ActiveRecord::Base) do
establish_connection :adapter => "sqlite3", :database => ":memory:"
connection.create_table(:people, :force => true) do |t|
end

extend ActiveHash::Associations::ActiveRecordExtensions
end

define_ephemeral_class(:Post, ActiveRecord::Base) do
establish_connection :adapter => "sqlite3", :database => ":memory:"
connection.create_table(:posts, :force => true) do |t|
t.integer :person_id
t.datetime :created_at
end

belongs_to :person
end
end

def define_school_classes
define_ephemeral_class(:Country, ActiveRecord::Base) do
establish_connection :adapter => "sqlite3", :database => ":memory:"
Expand Down Expand Up @@ -209,6 +235,22 @@ def define_doctor_classes
expect(patient.physicians).to contain_exactly(physician1, physician2)
end
end

describe "with a lambda" do
before do
define_person_classes
now = Time.now
@post_1 = Post.create! :person_id => 1, :created_at => now
@post_2 = Post.create! :person_id => 1, :created_at => 1.day.ago
Post.create! :person_id => 2, :created_at => now
Person.has_many :posts, lambda { order(created_at: :asc) }
end

it "should find the correct records" do
person = Person.create :id => 1
expect(person.posts).to eq([@post_2, @post_1])
end
end
end

describe ActiveHash::Associations::ActiveRecordExtensions do
Expand Down

0 comments on commit da9eeee

Please sign in to comment.