Skip to content

Instantly share code, notes, and snippets.

@matthewd
Last active December 22, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewd/6541214 to your computer and use it in GitHub Desktop.
Save matthewd/6541214 to your computer and use it in GitHub Desktop.
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