Rails 3:如何添加user_id – current_user.id配置?

我有这部分代码:

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的保护。

你可以在一个class轮上做以上,但我个人不喜欢。 我觉得这样比较清楚。 如果您想要进行error handling,可以像这样进行保存。

 if @comment.save # success else # error end 

试试这个:

 @comment = @post.comments.create(params[:comment].merge(:user => current_user))