ActiveRecord association with restriction
Driver has_many Cars Car has_one Owner
I would like to return Drivers which have Cars with owner_id=1 Here's the catch. I would like to return ALL Drivers with the Cars (with owner_id=1) eager loaded. If the Car's owner is not owner_id=1 I need to have the Driver.cars = [] (or nil)
The problem is when you eager load with a restriction on the association ALL DRIVERS DO NOT GET RETURNED.
When you use a Joins, The Car never 开发者_如何学Pythongets loaded as an active record.
Any thoughts? This problem is actually more complex than you think.
I've tried, joins, all, first, find with conditions, includes, etc. and every variation in between.
Here are some suggestions: You can wrap your "Driver has_many cars" in a code bracket and write it like a proper Ruby/Rails class so people reading your question will understand jsut by looking at it:
class Driver < ActiveRecord::Base
has_many :cars
end
class Car < ActiveRecord::Base
has_one :owner
end
Not to mention that it wouldn't hurt to paste Owner class in your post as well. Also Driver.cars
suggest that 'cars' is a class method and not AR association which is misleading. Also more natural thing would be defining you car method like this:
class Car < ActiveRecord::Base
belongs_to :owner
end
Finally, to answer your question. All quirks of eager loading, with your case as well I believe are docummented here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html under "Eager loading of associations" label.
精彩评论