Skip to content

Instantly share code, notes, and snippets.

Last active December 22, 2015 22:39
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
class Widget < AR::Base
has_many :parts
class Part < AR::Base
puts # => 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 =
o.widgets = Widget.where(color: 'blue').to_a!
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