Ruby on rails rails模型关联作者id

Ruby on rails rails模型关联作者id,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在使用rails的最佳实践来过滤代码。 评论属于帖子,帖子属于用户。 我的comments\u controller.rb文件如下所示 我的问题是:做这件事的最佳和正确的方法是什么?通常我建议在控制器特定的\u params函数中烘焙任何必需的参数。也就是说,这样做: def comment_params params.require(:comment).permit(:post_id, :body).merge( user: current_user ) end 然后,

我正在使用rails的最佳实践来过滤代码。 评论属于帖子,帖子属于用户。 我的
comments\u controller.rb
文件如下所示


我的问题是:做这件事的最佳和正确的方法是什么?

通常我建议在控制器特定的
\u params
函数中烘焙任何必需的参数。也就是说,这样做:

def comment_params
  params.require(:comment).permit(:post_id, :body).merge(
    user: current_user
  )
end
然后,当它到达你的控制器动作的时候,你已经很好地开始了

我倾向于使用
build
方法为
new
create
构建正确的对象:

def build_comment
  @comment = @post.comments.build(comment_params)
end
现在,如果您放松参数上的
require
约束,这将正确填充,但如何使其灵活取决于您。我发现这会为多轮编辑和需要设置默认值的第一轮编辑一致地填充和准备相同的对象

def comment_params
  params.require(:comment).permit(:post_id, :body).merge(
    user: current_user
  )
end
def build_comment
  @comment = @post.comments.build(comment_params)
end