Forum: Ruby on Rails using .find and :include with multiple levels of association

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 petermichaux (Guest)
on 2005-11-20 07:13
(Received via mailing list)
Hi,

I've tried to trim this example down to the minimum. Even though it
looks
complicated it is probably a fairly basic question about how
associations
and :include work. I want to do a find that is similar to the example
below.
The find statement doesn't work because AttributeValue doesn't have a
direct
association with Product: Product is one step further up the chain of
models. Can I somehow write the find statement without resorting to
:joins,
raw SQL or looping through the results to make some checks?

Thanks,
Peter

Class Product < ActiveRecord::Base
has_and_belongs_to_many :attributes
end

Class Attribute < ActiveRecord::Base
#not all attributes will be associated with a product
has_and_belongs_to_many :products
has_many :attribute_values
end

Class AttributeValue < ActiveRecord::Base
belongs_to :attribute
# cannot create a belongs_to association with Variation
end

Class Variation < ActiveRecord::Base
has_many :attribute_values
belongs_to :product

def distinguishing_attribute_values
AttributeValue.find(:all, :include=>[:attribute, :products],
:conditions=>"
product.id='#{product.id}'");
end

end
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 petermichaux (Guest)
on 2005-11-20 08:06
(Received via mailing list)
Hi,

The following works but I just keep thinking that this should be simpler

VirtualAttributeValue.find(:all, :include => :virtual_attribute,
:joins => 'LEFT OUTER JOIN products_virtual_attributes ON
products_virtual_attributes.virtual_attribute_id =
virtual_attributes.id',
:conditions=>
"products_virtual_attributes.product_id=#{product.id<http://product.id>
}
AND virtual_attribute_values.variation_id = '#{id}'")

Any suggestions to make is simpler without that :joins? seems like I
should
be able to take better advantage of the existing chain of models through
associations.

-Peter
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 petermichaux (Guest)
on 2005-11-20 08:26
(Received via mailing list)
I have it down to the following statement. Maybe this is the best it can
be?

virtual_attribute_values.find(:all, :include => :virtual_attribute,
:joins => 'LEFT OUTER JOIN products_virtual_attributes ON
products_virtual_attributes.virtual_attribute_id =
virtual_attributes.id',
:conditions=>
"products_virtual_attributes.product_id=#{product.id<http://product.id>
}")
This topic is locked and can not be replied to.