Getting data from a through table

im using has_many through and the through table has some data i want
but i cant seem to access it using straight rails

class AttributeObjects < ActiveRecord::Base belongs_to :attributes belongs_to :objects end

class Attributes < ActiveRecord::Base
has_many :attribute_objects
has_many :objects, :through => :attribute_objects
end

class Objects < ActiveRecord::Base
has_many :attribute_objects
has_many :attributes, :through => :attribute_objects
end

now imagine that attribute_objects also contains a rating
so when i say, object.attributes, id like to get the rating too
that doesnt seem to be possible with the has_many relationship
if i could force the join on the object attributes to bring the
attribute_objects fields also…maybe

i think i have to write custom sql for this

On 19 March 2010 03:49, dan [email protected] wrote:

now imagine that attribute_objects also contains a rating
so when i say, object.attributes, id like to get the rating too
that doesnt seem to be possible with the has_many relationship
if i could force the join on the object attributes to bring the
attribute_objects fields also…maybe

If you want to access properties of AttributeObjects [1], you can
iterate the collection of them, not the collection of attributes.
So instead of:

@object.attributes.each do |attribute|
attribute.name …
end

you do this:
@object.attribute_objects.each do |attribute_object|
attribute_object.attribute.name …
attribute_object.rating …
end

i think i have to write custom sql for this

You can if you want… but you don’t have to.
You can possibly use the “:finder_sql” option of the association to
specify your own conditions for populating the collection (I’ve been
fiddling with it here for 10mins, and not got it working… post up
some working code if it does it for you :slight_smile:

[1] All your class names are plural; they should really be singular…

thanks for the suggestions

attributes is a self inherited table
so i need to get them i order of top level and down
this is part of my current solution

has_many :objects_attributes do
def top_level
all(:joins => :attribute, :conditions => “attributes.parent_id
is null”)
end

def children(id)
  all(:joins => :attribute, :conditions => ["attributes.parent_id

= ?", id])
end
end

this allows me to access all fields in order desired
thanks for your help