Reputation: 1089
Say there're two models : User and Post, i want to keep track of who has read which post, and who writes which post, which user favorites which posts etc. Then i come up with the following solution:
class User < ActiveRecord::Base
has_many :writings
has_many :posts, :through => :writings
has_many :readings
has_many :posts, :through => :readings
#..
end
class Post < ActiveRecord::Base
has_many :writings
has_many :posts, :through => :writings
#...
end
and setting up the intermediate models - Writing, Reading. this works, but finally i find out that when i writing this
@user.posts #...
the returned array contains housekeeping information both for writings and readings. How can i solve this problem.
Upvotes: 0
Views: 866
Reputation: 23450
You want something like this:
class User < ActiveRecord::Base
has_many :writings
has_many :posts, :through => :writings
has_many :readings
has_many :read_posts, :through => :readings, :class_name => "Post"
#..
end
By giving the association name something other than just :posts you can refer to each one individually. Now...
@user.posts # => posts that a user has written via writings
@user.read_posts # => posts that a user has read via readings
Upvotes: 10