0

我正在用嵌套资源构建一个 crud。

Post has_many :comments和我的comments belongs_to :userbelongs_to :post。当我添加新评论时,我目前正在评论控制器的创建操作中执行类似的操作:

@post = Post.where(id: params[:post_id]).first
@post_comments = @post.post_comments.build
@post_comments.update_attributes(params[:post_comment])
@post_comments.user = current_user

if @post_comments.save
  ...

我还看到了这篇文章:https ://stackoverflow.com/a/5978113这似乎在做我正在做的事情。

这似乎不稳定,我不确定我是否正确执行此操作。有没有更好的办法?最佳做法是什么?

4

1 回答 1

2

我不知道任何已定义的最佳实践,但使用您的代码,您不需要调用update_attributes. 有 2 种方法可以保存两个外键(实际上是 4 种方法,如果您要构建来自用户的评论)

第一个选项:

params[:post_comment].merge!(user_id: current_user.id)
@post = Post.where(id: params[:post_id]).first
@post_comment = @post.post_comments.build(params[:post_comment])

if @post_comment.save
  ...
else
  ...
end

第二种选择:

@post = Post.where(id: params[:post_id]).first
@post_comment = @post.post_comments.build(params[:post_comment])
@post_comment.user = current_user

if @post_comment.save
  ...
else
  ...
end

不过请注意,如果您正在处理单数资源,则应该使用单数@post_comments形式@post_comment

于 2013-03-31T12:26:48.330 回答