gpt4 book ai didi

ruby-on-rails - 在 Rails 4 中向模型添加注释和强参数抛出错误

转载 作者:行者123 更新时间:2023-12-02 05:00:26 27 4
gpt4 key购买 nike

昨晚我开始玩 Rails 4。我正在制作一个简单的博客类型的应用程序来熟悉一些变化。我有使用默认脚手架的帖子。

我决定在没有脚手架的情况下添加评论,但当我尝试保存对帖子的评论时出现此错误:

ActiveModel::ForbiddenAttributesError in CommentsController#create

在错误页面上请求参数:

{"utf8"=>"✓",
"authenticity_token"=>"jkald9....",
"comment"=>{"commenter"=>"Sam",
"body"=>"I love this post!"},
"commit"=>"Create Comment",
"post_id"=>"1"}

这是评论 Controller 的创建操作:

    class CommentsController < ApplicationController
def create
@post = post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end

private

def comment_params
params.require(:comment).permit(:commenter, :body, :post_id)
end
end

这是我的评论的最基本的迁移。

class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :post, index: true

t.timestamps
end
end
end

我在使用强类型参数时做错了什么?或者也许 Rails 4 中还有其他我遗漏的变化?

最佳答案

有点疏忽,但我想我会回答这个问题,以防其他人正在将类似的 Rails 3 代码移植到 Rails 4。

您需要像这样将 comment_params 传递到批量分配中:

@comment = @post.comments.create(comment_params)

关于ruby-on-rails - 在 Rails 4 中向模型添加注释和强参数抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17179553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com