Peter Michaux
2005-Nov-20 06:13 UTC
using .find and :include with multiple levels of associations
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 _______________________________________________ Rails mailing list Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org http://lists.rubyonrails.org/mailman/listinfo/rails
Peter Michaux
2005-Nov-20 07:03 UTC
Re: using .find and :include with multiple levels of associations
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 _______________________________________________ Rails mailing list Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org http://lists.rubyonrails.org/mailman/listinfo/rails
Peter Michaux
2005-Nov-20 07:23 UTC
Re: using .find and :include with multiple levels of associations
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> }") _______________________________________________ Rails mailing list Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org http://lists.rubyonrails.org/mailman/listinfo/rails