简体   繁体   English

Rails-如何在帖子评论中插入user_id?

[英]Rails - How can I insert the user_id to a comment on a post?

Probably a simple question, but I'm just learning Rails and tryin to get comments to post to my database. 可能是一个简单的问题,但我只是在学习Rails和tryin,以获取要发布到数据库的评论。 When I post, no error is thrown but the record is not created. 当我发布时,不会引发任何错误,但是不会创建记录。

def create

    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment].permit(:comment))

    redirect_to post_path(@post)

end

Posts and comments have a typical nested relationship. 帖子和评论具有典型的嵌套关系。 I believe the problem lays with a column in my comments table called 'user_id' that should store the relationship of a comment to a user. 我认为问题出在我的评论表中名为“ user_id”的列,该列应存储评论与用户的关系。

How can I set this column in the above code to have the value of 'current_user'? 如何在上面的代码中将此列设置为'current_user'的值?

Many thanks, Michael. 非常感谢,迈克尔。

Combining previous answers, try 结合以前的答案,尝试

@post   = current_user.posts.find(params[:comment][:post_id])
@comment = @post.comments.build(params[:comment].permit(:comment))
@comment.save!

or perhaps 也许

@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment].permit(:comment))
@comment.user_id = current_user.id
@comment.save!

Supposing your form already supplies post_id and that you are using the Rails Tutorial method "current_user", plus that the user supposingly has_many :posts , you can fill all of the fields with this code: 假设您的表单已经提供了post_id,并且您正在使用Rails教程方法“ current_user”,并且假设用户具有has_many :posts ,那么您可以使用以下代码填充所有字段:

@post   = current_user.posts.find(params[:comment][:post_id])
@comment= @post.comments.create(params[:comment][:comment])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM