views:

139

answers:

2

I hope someone has already experienced this. Please help me, how can i solve this problem:

class Article < ActiveRecord::Base
  belongs_to :author
  belongs_to :publisher
  has_one :address, :through => :publisher
end

class Author < ActiveRecord::Base
  has_many :articles
  has_many :addresses, :through => :articles, :source => :address
end

I try to get "addresses" for "author", and i get this error in console:

ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source reflection macro :has_one :through for has_many :addresses, :through => :articles.  Use :source to specify the source reflection.

but author.articles[0].address works fine.

I hope you give me advice, how can i solve it. Thanks.

A: 

AR does not like sourcing a has_many through a has_one. But you can easily get all the addresses with this method on Author:

def addresses
  articles.map {|article| article.address }
end
Jonathan Julian
thaold
I don't think AR relationships can do it. This one line is not a bad solution though - it's very clear what the intent is, and you can wrap it into a method so it *looks* like an association.
Jonathan Julian
A: 

This solution also worked well for different relation types.

e.g. User.registrations.join_table.periods

but you -can't- apply active_record methods on what is mapped.

e.g. user.periods(:order => :date) e.g. user.periods.model etc..

thanks

c-a