Reputation: 195
I have two models A and B where:
A has_one B
I therefore have added a foreign key to A that associates every instance of A with the id of an instance of B. Note that I do know want this to be a 1-1 relationship.
How can I use A.find() to get all the instances of A that are associated with an instance of B with a certain attribute from B (B.name for example)?
I know that this can be done with a SQL join between the two tables but is there an elegant way of doing this in ROR?
Upvotes: 0
Views: 133
Reputation: 12273
Assuming you have the right associations setup:
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Client.joins(:orders).where(:orders => {:created_at => time_range})
This is from the Active Record Querying guide
Upvotes: 1
Reputation: 599
has_one
association requires foreign key in belonging model.
Please take a look on RailsGuides - http://guides.rubyonrails.org/association_basics.html#the-has_one-association
Upvotes: 0