Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何使用ActiveRecord关联指定rails中模型之间的多个关系_Ruby On Rails_Activerecord - Fatal编程技术网

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