添加对用户和post模型的评论(Ruby on Rails)
我是Rails的新手。 我正在构建我的第一个应用程序 – 简单的博客。 我有User和Post模型,每个用户可以写很多post。 现在我想添加评论模型,其中每个post可以有很多评论,并且每个用户也可以评论任何其他用户创建的任何post。
在评论模型我有
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中正确定义创建动作呢? 谢谢。
更新:
的routes.rb
resources :posts do resources :comments end
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并且只有在我删除validates :user_id, presence: true
时才validates :user_id, presence: true
来自comment.rb的validates :user_id, presence: true
字符串
有什么建议?
在你的方式你应该这样:
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作为强参数删除。 希望这会帮助你 。
协会
为了给出这里发生的事情的定义,您必须记住,无论何时创建记录,您基本上都在填充数据库。 您的关联是使用foreign_keys
定义的
当你问如何“为User
和Post
模型添加评论”时 – 底线是你没有; 您在Comment
模型中添加Comment
,并可以将其与User
和Post
相关联:
#app/models/comment.rb Class Comment < ActiveRecord::Base belongs_to :user belongs_to :post end
这提示Rails默认在Comment
模型中查找user_id
和post_id
。
这意味着如果您想直接创建注释,只需根据需要填充foreign_keys
(或使用Rails对象填充它们),就可以将它与这些关联中的任何一个相关联。
因此,当您想要保存comment
,您可以这样做:
#app/controllers/comments_controller.rb Class CommentsController < ApplicationController def create @comment = Comment.new(comment_params) end private def comment_params params.require(:comment).permit(:user_id, :post_id, :etc) end end
相反,您可以使用标准的Rails对象来处理它(因为已接受的答案已指定)
Class CommentsController < ApplicationController before_action :set_user before_action :set_post def create @comment = @post.comments.create(comment_params) if @comment.save redirect_to @post else flash.now[:danger] = "error" end end private set_post @post = User.posts.find(params[:post_id]) end set_user @user = User.find(params[:user_id]) end comment_params params[:comment].permit() end