Ale*_*der 8 ruby ruby-on-rails ruby-on-rails-4
我是Rails的新手.我正在构建我的第一个应用程序 - 简单的博客.我有User和Post模型,每个用户可以写很多帖子.现在我想添加评论模型,每个帖子可以有很多评论,每个用户也可以评论任何其他用户创建的任何帖子.
在评论模型中我有
id \ body \ user_id \ post_id
列.
模型关联:
user.rb
has_many :posts, dependent: :destroy
has_many :comments
Run Code Online (Sandbox Code Playgroud)
post.rb
has_many :comments, dependent: :destroy
belongs_to :user
Run Code Online (Sandbox Code Playgroud)
comment.rb
belongs_to :user
belongs_to :post
Run Code Online (Sandbox Code Playgroud)
那么如何在CommentsController中正确定义创建动作呢?谢谢.
更新:
routes.rb
resources :posts do
resources :comments
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
结果是
--- !ruby/hash:ActionController::Parameters
utf8: ?
authenticity_token: rDjSn1FW3lSBlx9o/pf4yoxlg3s74SziayHdi3WAwMs=
comment: !ruby/hash:ActionController::Parameters
body: test
action: create
controller: comments
post_id: '57'
Run Code Online (Sandbox Code Playgroud)
我们可以看到它不会发送user_id,只有当我validates :user_id, presence: true从comment.rb中删除字符串时才有效
有什么建议?
小智 11
在你的方式你应该把它:
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
Run Code Online (Sandbox Code Playgroud)
此外,您应该将comment_params中的user_id作为强参数删除.希望这会帮助你 .
协会
为了给出这里发生的事情的定义,您必须记住,无论何时创建记录,您基本上都要填充数据库.您的关联定义为foreign_keys
当你问如何"添加评论User和Post模型"时 - 底线是你没有; 您向Comment模型添加注释,并可以将其与User和Post:
#app/models/comment.rb
Class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
Run Code Online (Sandbox Code Playgroud)
这会提示Rails 默认查找user_id并post_id在Comment模型中查找.
这意味着如果您想直接创建注释,只需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
Run Code Online (Sandbox Code Playgroud)
相反,您可以使用标准的Rails对象来处理它(因为已接受的答案已指定)
| 归档时间: |
|
| 查看次数: |
15574 次 |
| 最近记录: |