向 User 和 Post 模型添加评论(Ruby on Rails) [英] Add Comment to User and Post models (Ruby on Rails)
问题描述
我是 Rails 的新手.我正在构建我的第一个应用程序 - 简单的博客.我有 User 和 Post 模型,每个用户可以写很多帖子.现在我想添加评论模型,每个帖子可以有很多评论,并且每个用户都可以评论任何其他用户创建的任何帖子.
在评论模型中我有
I'm new to Rails. I'm building my first app - simple blog. I have User and Post models, where each user can write many posts. Now I want to add Comment model, where each post can have many comments, and also each user can comment on any post created by any other user.
In Comment model I have
id \ body \ user_id \ post_id
列.
模型关联:
user.rb
has_many :posts, dependent: :destroy
has_many :comments
post.rb
has_many :comments, dependent: :destroy
belongs_to :user
comment.rb
belongs_to :user
belongs_to :post
那么如何在 CommentsController 中正确定义创建操作?谢谢.
So how do I correctly define create action in CommentsController? Thank you.
更新:
路线.rb
resources :posts do
resources :comments
end
comments_controller.rb
comments_controller.rb
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
if @comment.save
redirect_to @post
else
flash.now[:danger] = "error"
end
end
结果是
--- !ruby/hash:ActionController::Parameters
utf8: ✓
authenticity_token: rDjSn1FW3lSBlx9o/pf4yoxlg3s74SziayHdi3WAwMs=
comment: !ruby/hash:ActionController::Parameters
body: test
action: create
controller: comments
post_id: '57'
正如我们所看到的,它不会发送 user_id 并且只有当我从 comment.rb 中删除 validates :user_id,presence: true
字符串时才起作用
As we can see it doesnt send user_id and works only if I delete validates :user_id, presence: true
string from comment.rb
有什么建议吗?
推荐答案
你应该按照自己的方式来:
In your way you should put this:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
@comment.user_id = current_user.id #or whatever is you session name
if @comment.save
redirect_to @post
else
flash.now[:danger] = "error"
end
end
并且您还应该从 comment_params 中删除 user_id 作为强参数.希望这对你有帮助.
And also you should remove user_id from comment_params as strong parameters . Hope this will help you .
这篇关于向 User 和 Post 模型添加评论(Ruby on Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!