Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.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 通过与多个关联的关联创建_Ruby On Rails_Polymorphism_Associations - Fatal编程技术网

Ruby on rails 通过与多个关联的关联创建

Ruby on rails 通过与多个关联的关联创建,ruby-on-rails,polymorphism,associations,Ruby On Rails,Polymorphism,Associations,这一定是一种很常见的情况,但我不明白: 我有一个多态评论模型,一个帖子模型和一个用户模型。 这是我的关联设置: class Post < ActiveRecord::Base has_many :comments, :as => :commentable end class User < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base attr_acc

这一定是一种很常见的情况,但我不明白:

我有一个多态评论模型,一个帖子模型和一个用户模型。 这是我的关联设置:

class Post < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  attr_accessible :content

  belongs_to :commentable, polymorphic: true
  belongs_to :user
end
这将起作用,但我必须使评论的用户id attr_可访问。出于安全考虑,我不想这么做。。。有没有一种方法可以以另一种方式将评论和用户关联起来

谢谢大家的帮助

以下是您需要的:

user has_many :posts
user has_many :comments, :through :posts

post has_many :comments
post belongs_to :user

comment belongs_to :user
comment belongs_to :post
用户是帖子和评论的通用实体。只有在帖子存在时,用户才能对帖子发表评论(因此,用户、评论和帖子之间的关系非常密切)。我认为其余的关系都是不言自明的

例如:

user.posts.create(<post params>)

user.posts.find(1).comments.create(<comment params>)

user.posts #retrieve all posts
user.posts.find(1).comments #retrieve all comments by a user on the first post 

现在,您可以使用键检索post对象,并使用它执行您想要的任何操作。您的用户现在将无法更改url以更改帖子id。为了使其更加健壮,您可以加密密钥(签出),在路由中显示加密的密钥,并解密密钥以获取正确的对象


总而言之,您仍然需要公开一个属性来唯一标识post对象。

我不明白您的要求。你能举一个例子说明这是一个问题吗?我在帖子中添加了一个例子。但是如果一个用户对他没有生成的帖子发表评论怎么办?在这种情况下,我无法使用user.posts.find…感谢您的帮助,但我仍然不确定。更新中的行是否可以不进行注释。post\u id attr\u是否可以访问?因为这就是问题的关键所在。
user.posts.create(<post params>)

user.posts.find(1).comments.create(<comment params>)

user.posts #retrieve all posts
user.posts.find(1).comments #retrieve all comments by a user on the first post 
post = Post.find(params[:id]) 
user.comments.create(post_id => post.id, <other params>)
/posts/:id, /posts/:id/edit
/posts/:key, /posts/:key/edit