Rails 3:如何添加 user_id - current_user.id 关联? [英] Rails 3: How to add user_id - current_user.id assotiations?

查看:74
本文介绍了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-一个控制器

但是我的评论表中还有一列user_id".如何将 user_id 与 current_user.id 关联?

But I have one more column "user_id" in my comment table. How can I assotiate user_id with current_user.id?

ps.我的应用中有工作示例:

ps. I have working example in my app:

@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 的保护.

you could put the user_id in the params but that wouldnt be safe. user_id shouldnt be in 'attr_accessable' so it will be protected for mass_assignment.

您可以在一个衬垫中完成上述操作,但我个人不喜欢那样.我这样想,就比较清楚了.如果你想进行错误处理,你可以像这样保存.

You could do the above in a one liner but personally i dont like that. I think like this, it is more clear. If you want to have error handling you could do the save like this.

if @comment.save
  # success
else
  # error
end

这篇关于Rails 3:如何添加 user_id - current_user.id 关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆