【问题标题】:Create through association with multiple associations通过与多个关联的关联创建
【发布时间】:2013-10-15 14:01:13
【问题描述】:

这一定是很常见的情况,但我想不通:

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

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

现在,我不希望 commentable_id 和 user_id 成为 attr_accesible,因为我不希望它们受到批量分配。我知道解决方案是通过关联创建评论,但我怎样才能为这两个关联做到这一点?

编辑:

示例: 我在一个帖子中,我想发表评论。假设我有 user_id。这样做的方法是:

@post.comments.create(user_id: 1, content: "bla bla")

这会起作用,但我必须使评论的 user_id attr_accessible。出于安全原因,我不想这样做...有没有办法以另一种方式关联评论和用户?

感谢所有帮助者!

【问题讨论】:

  • 我不明白你的要求。你能举个例子吗?
  • 我在帖子中添加了一个示例。

标签: ruby-on-rails polymorphism associations


【解决方案1】:

这是你需要的:

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

用户是帖子和 cmets 的通用实体。只有当帖子存在时,用户才能对帖子发表评论(因此用户、cmets 和帖子之间的 has_many_through 关系)。我认为其余的关系是不言自明的。

示例:

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>)

更新 2

检索 post 对象以更改基础数据很重要。您可以在您的帖子表中添加一个新列,例如键(生成一个十六进制值),它与帖子的 id 具有一对一的映射关系。您还可以修改路由以显示此键而不是默认的帖子 ID。 即改变

/posts/:id, /posts/:id/edit

/posts/:key, /posts/:key/edit

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

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

【讨论】:

  • 但是如果用户在他没有生成的帖子上遇到了怎么办?在那种情况下,我无法使用 user.posts.find...
  • 感谢您的帮助,但我仍然不相信。在不使 Comment.post_id attr_accesible 的情况下,您的更新中的行是否可行?因为这就是问题的全部意义所在。
猜你喜欢
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 2014-02-05
相关资源
最近更新 更多