[英]Rails form params not being saved
我是Ruby on Rails的新手,我在脚手架控制器上苦苦挣扎。 我做了一个嵌套的资源,将我的评论放在帖子中。
class Post < ActiveRecord::Base
validates :name, :presence => true
validates :title, :presence => true, :length => { :minimum => 5 }
has_many :comments
end
class Comment < ActiveRecord::Base
validates :commenter, :presence => true
validates :body, :presence => true
belongs_to :post
end
控制器的简化版本是
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# omited new, index, show...
# POST /comments
# POST /comments.json
def create
post = Post.find(params[:post_id])
@comment = post.comments.create(params[:comment].permit(:name, :title, :context))
respond_to do |format|
if @comment.save
format.html { redirect_to([@comment.post, @comment], notice: 'Comment was successfully created.') }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
post = Post.find(params[:post_id])
@comment = post.comments.find(params[:comment])
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:commenter, :body, :post)
end
end
当我填写表格时,出现以下异常:
有2个错误禁止保存此评论:评论者不能为空正文不能为空
我尝试了本指南,但我认为它与Rails 4不兼容。
看来您在create
操作中明确permitting
不同的属性集。
您应该像在update
操作中所做的那样,将您的create
操作更新为使用comment_params
。 之所以成为您的Comment
,绝对是因为期望Commenter
和Body
而不是您在create
动作中允许的:name, :title, :context
。
将controller
的create
操作更新为:
# POST /comments
# POST /comments.json
def create
...
@comment = post.comments.create(comment_params)
...
end
您正在从Post
params
属性中读取( :name, :title, :context
),但是您需要阅读Comments
属性( :commenter, :body
)
替换为:
@comment = post.comments.create(params[:comment].permit(:name, :title, :context))
与
@comment = post.comments.create(params[:comment].permit(:commenter, :body))
或者,更好的是:
@comment = post.comments.create(comment_params)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.