Ruby on rails 如何使用ActiveRecord关联指定rails中模型之间的多个关系
假设有两种模型:用户和帖子,我想跟踪谁读了哪个帖子,谁写了哪个帖子,哪个用户最喜欢哪个帖子等等。然后我提出了以下解决方案:Ruby on rails 如何使用ActiveRecord关联指定rails中模型之间的多个关系,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,假设有两种模型:用户和帖子,我想跟踪谁读了哪个帖子,谁写了哪个帖子,哪个用户最喜欢哪个帖子等等。然后我提出了以下解决方案: class User < ActiveRecord::Base has_many :writings has_many :posts, :through => :writings has_many :readings has_many :posts, :through => :readings #.. end class Post &
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
返回的数组包含写入和读取的内务管理信息。我怎样才能解决这个问题。你想要这样的东西:
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
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
@user.posts # => posts that a user has written via writings
@user.read_posts # => posts that a user has read via readings