Calling an association through another, without hm:t?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Order < AR::Base | |
has_many :widgets | |
has_many :parts, through: :widget | |
end | |
class Widget < AR::Base | |
has_many :parts | |
end | |
class Part < AR::Base | |
end | |
puts order.parts.to_sql # => combined parts from all the widgets in the order | |
# but what if I've got some Widgets from elsewhere?... | |
puts Widget.where(color: 'blue').parts.to_sql # => nope. | |
Order.transaction do | |
o = Order.new | |
o.widgets = Widget.where(color: 'blue').to_a | |
o.save! | |
puts o.parts.to_sql | |
raise ActiveRecord::Rollback | |
end # => almost what I want, and yet entirely not | |
puts Part.where(widget_id: Widget.where(color: 'blue')).to_sql | |
# => works in this case, but a more complex association is not so easily inverted |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment