2

有什么方法可以创建属于其他两个模型的模型对象,例如,如果我的用户有很多帖子,然后帖子可以有很多评论,评论既属于用户又属于帖子。如果我做 post.comments.create() 它只会将帖子与评论相关联,如果我做 user.comments.create() 那么它将关联用户。如果我想将两者与评论相关联,那么方法是什么。我知道我可以使用多态关联,但还有其他方法吗?

4

3 回答 3

3

首先,当您谈论关联时,您必须记住我们build不是create。做你需要的一个非常简单的方法是做

    class Comment < ActiveRecord::Base
      belongs_to :user
   end

并且不要忘记在用户中添加关系的另一端:

 class User < ActiveRecord::Base
  has_many :comments
 end

现在,我知道您必须在评论表中创建了一个字段 user_id。如果没有,您需要通过此迁移添加它。

rails g migration add_user_id_to_comments user_id:string

现在做一个rake db:migrate

或者,一个更好的方法将是 .

在创建模型注释时,您添加 users:references 在迁移行中,如下所示

rails g model Comment text:string post:references user:references

这样,关系的一侧将自动添加到模型中,并且 user_id 和 post_id 字段将自动添加到您的评论表中。

回到你的问题。如果您找不到像这样的其他方法,请在隐藏字段中传递用户 ID:

<%= hidden_field_tag "userid", current_user.id%>

我希望你有当前用户定义。现在您可以在这样的评论的控制器中接受它

If params[:userid]
 user_id = params[:userid]
end

您可以在评论控制器的创建操作中将其包含在保存功能之前。

希望这可以帮助

干杯!

于 2013-09-24T05:31:18.047 回答
2

您可以将 belongs_to 与这两个模型一起使用。唯一的区别是,在创建评论时,您必须明确提及您未通过其创建的模型的 ID。我举个例子:

class Comment
  belongs_to :user
  belongs_to :post
end

comment = post.comments.create(user_id: some_user_id)

由于我通过帖子评论关系创建了评论,因此帖子 ID 将自动插入到评论的post_id属性中。我特别提到了user_id,这comment.user将返回具有 id 的用户some_user_id

编辑

创建评论时,要使用params哈希中的评论属性,请使用以下内容:

comment = post.comments.build(params[:comment])
comment.user_id = some_user_id
comment.save
于 2013-09-24T05:29:01.623 回答
0

像这样创建评论可能更直观:

comment = Comment.create(user_id: user-you-want-to-associate.id, post_id: post-you-want-to-associate.id)

于 2015-08-17T17:59:51.660 回答