我有这部分代码:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
http://guides.rubyonrails.org/getting_started.html#generating-a-controller
但是我的评论表中多了一列“user_id”。如何将 user_id 与 current_user.id 关联起来?
ps。我的应用程序中有工作示例:
@post = Post.new(params[:post])
@post.user_id = current_user.id
最佳答案
我会说这样的话。
@comment = @post.comments.build(params[:comment])
@comment.user_id = current_user.id
@comment.save
您可以将 user_id 放入参数中,但这并不安全。 user_id 不应该位于“attr_accessable”中,因此它将受到mass_assignment 的保护。
您可以在一个衬垫中完成上述操作,但我个人不喜欢这样做。我想这样一来,就更清楚了。如果您想进行错误处理,可以像这样进行保存。
if @comment.save
# success
else
# error
end
关于ruby-on-rails - Rails 3 : How to add user_id - current_user. id 关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7128214/