Skip to content

Instantly share code, notes, and snippets.

@matthewd
Last active Dec 22, 2015
Embed
What would you like to do?
Calling an association through another, without hm:t?
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