Using .find and :include with multiple levels of association


#1

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


#2

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.idhttp://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


#3

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.idhttp://product.id
}”)