I have a User model, that may have many activities ( I’m keeping track of some of the actions performed by my users, for statistical purposes )
class User < ActiveRecord::Base
has_many :activities
has_many :histories,:through => :activities # ?
end
class Activity < ActiveRecord::Base
belongs_to :user
belongs_to :history, :polymorphic => true
end
class BrowsingHistory < ActiveRecord::Base
has_many :activities,:as => :histories
end
class LoginHistory < ActiveRecord::Base
has_many :activities,:as => :histories
end
...
The Activity class has a history_type:string , a history_id:integer and a user_id:integer, and I want it to be able to hold BrowsingHistory or LoginHistory objects.
I’ve worked pretty little with polymorphic associations, and from what I have thus far, I keep getting the error: ActiveRecord::HasManyThroughAssociationPolymorphicSourceError:Cannot have a has_many :through association 'User#histories' on the polymorphic object 'History#history'. I read through some of the related questions on this topic, but I cannot figure out a solution.
EDIT: I think I got it ( console tests seem to work ), could you please confirm?
class User < ActiveRecord::Base
has_many :activities
has_many :login_histories,:through => :activities,:source => :history,:source_type => "LoginHistory"
end
class Activity < ActiveRecord::Base
belongs_to :user
belongs_to :history, :polymorphic => true
end
class BrowsingHistory < ActiveRecord::Base
has_many :activities,:as => :history
has_many :users,:through => :activities
end
class LoginHistory < ActiveRecord::Base
has_many :activities,:as => :history
has_many :users,:through => :activities
end
This worked fine: