gpt4 book ai didi

ruby-on-rails - rails 4 ActiveModel::ForbiddenAttributesError

转载 作者:行者123 更新时间:2023-12-03 10:31:43 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





ActiveModel::ForbiddenAttributesError when creating new user

(7 个回答)


7年前关闭。




我尝试使用 rails 4 做一个简单的创建

我的 Controller :

class AdsController < ApplicationController

def new
@ad = Ad.new
end

def create
@ad = Ad.new(params[:ad])
@ad.save
end

def show
@ad = Ad.find(params[:id])
end

def index
@ads = Ad.first(3)
end


private
def ad_params
params.require(:ad).permit(:title, :price, :description)
end
end

形式:
<%= form_for @ad do |p| %>
<p><%= p.text_field :title %></p>
<p><%= p.text_field :price %></p>
<p><%= p.text_area :description %></p>
<p><%= p.submit %></p>
<% end %>

从我的角度来看没问题,但我收到了这个错误 ActiveModel::ForbiddenAttributesError我做错了什么?

更新:

我的问题是在创建操作中将错误的值传递给新方法:解决方案是传递 ad_params给它

最佳答案

我建议跳过更新以便您的代码正常工作

您的问题可能不在您的 Controller 中,而在您的模型中:
检查以查看您的属性是否可以使用 follow 标签访问

attr_accessible :title, :price, :description

Rails 4 的做法与我的理解略有不同,以前的 SO 答案提供了一些很好的链接:
How is attr_accessible used in Rails 4?

每当您从数据库访问内容时,您都需要使用 attr_accessible/Strong Params。

更新

哦,年轻,没有意识到 Rails 4 使用了强参数。我知道 OP 已经解决了他最初的问题,但我将更正这个问题,以便它实际上可以用作正确答案。

这将是 Controller 级别的问题,因为 Rails 4 要求您将 Controller 中的属性列入白名单。
Ad.create(params[:ad].require(:ad).permit(:title, :price, :description))

大多数情况下,您将允许在创建和更新操作中使用相同的参数,因此最好将其移动到 Controller 中的自己的方法中。
Ad.create(ad_params)
def ad_params
params.require(:ad).permit(:title, :price, :description)
end

正如 OP 在他的评论中指出的那样,他实现的 allowed_pa​​rams 方法不是从许可证中调用的。

关于ruby-on-rails - rails 4 ActiveModel::ForbiddenAttributesError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17868427/

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