Has_many :through and has_one association


#1

Can’t get the following to work:

class Forum < ActiveRecord::Base
has_many :topics
has_many :recent_posts, :through => :topics, :source => :last_post,
:order => ‘posted_at DESC’
end

class Topic < ActiveRecord::Base
has_one :last_post, :class_name => ‘Post’, :order => ‘posted_at DESC’
end

class Post < ActiveRecord::Base
belongs_to :topic
end

Forum.find(:first).offers

I get the following error:

ActiveRecord::HasManyThroughSourceAssociationMacroError:
ActiveRecord::HasManyThroughSourceAssociationMacroError
from
c:/InstantRails-1.0/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/reflection.rb:181:in
check_validity!' from c:/InstantRails-1.0/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/associations/has_many_through_association.rb:6:ininitialize’
from
c:/InstantRails-1.0/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/associations.rb:876:in
`offers’
from (irb):93

Any clues?

Cheers,

~ Mark D.


#2

Forum.find(:first).offers

Sorry I meant:

Forum.find(:first).recent_posts


#3

I would suggest fully qualifying the :order fields as one thing to
try. I do not see anything obvious that is wrong with the models.

Can you post the migrations as well? It may be a miss-match between
the models and the tables.

Michael

On Mar 17, 8:24 am, Mark D. removed_email_address@domain.invalid


#4

It seems the has_one assoc. on the Topic model is why this doesn’t work.
It returns a single item as opposed to an array containing a single
item.

I ended up doing this:

class Forum < ActiveRecord::Base

class Forum < ActiveRecord::Base
has_many :topics
has_many :recent_topics, :class_name => ‘Topic’, :finder_sql =>
‘SELECT DISTINCT topics.* FROM (’ +
'SELECT topics.* ’ +
'FROM forums ’ +
'INNER JOIN topics ON forums.id = topics.forum_id ’ +
'INNER JOIN posts ON topics.id = posts.topic_id ’ +
'WHERE forums.id = #{id} ’ +
‘ORDER BY posts.posted_at DESC’ +
‘) AS topics’

has_many :recent_posts, :through => :topics, :source => :last_post,
:order => ‘posted_at DESC’
end

class Topic < ActiveRecord::Base
has_many :last_post, :class_name => ‘Post’, :order => ‘posted_at
DESC’, :limit => 1
end

class Post < ActiveRecord::Base
belongs_to :topic
end

As you can see it’s not very pretty. In addition I had to do some pretty
crazy custom finder_sql to add the ‘recent_topics’ assoc.

After several hours I gave up trying to find a DRY solution. Any
improvements welcomed!