rails 4 ActiveModel::ForbiddenAttributesError [英] rails 4 ActiveModel::ForbiddenAttributesError

查看:32
本文介绍了rails 4 ActiveModel::ForbiddenAttributesError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 rails 4 进行简单的创建

I try to do a simple create using rails 4

我的控制器:

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我做错了什么?

from my point of view it's ok but I got this error ActiveModel::ForbiddenAttributesError what I'm doing wrong?

更新:

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

my problem was passing wrong value to new method in create action: the solution was to pass ad_params to it

推荐答案

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

您的问题可能不在于您的控制器,而在于您的模型:检查以查看您的属性是否可以通过以下标签访问

Your problem is probably not in your controller, but your model: Check to see your attributes are accessible with the follow tag

attr_accessible :title, :price, :description

Rails 4 确实与我的理解略有不同,这个以前的 SO 答案提供了一些很好的链接:在 Rails 4 中如何使用 attr_accessible?

Rails 4 does do it a little different from what I understand, this previous SO answer provided some good links: How is attr_accessible used in Rails 4?

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

You need to use attr_accessible/Strong Params whenever you're accessing things from the database.

更新

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

Oh to be young, and not realize Rails 4 uses Strong Params. I understand the OP has already solved his original problem, but I'm going to correct this so it could actually be used as the right answer.

这将是控制器级别的问题,因为 Rails 4 要求您将控制器中的属性列入白名单.

This would be a controller level issue, as Rails 4 requires you to whitelist attributes in the controller.

Ad.create(params[:ad].require(:ad).permit(:title, :price, :description))

大多数情况下,您将允许在 create 和 update 操作中使用相同的参数,因此最好将其移动到控制器中自己的方法中.

Most of the time you'll be permitting the same params in the create and update action, so it's best to move it into its own method within the controller.

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

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

As OP pointed out in his comment, the permitted_params method he implemented was not being called from the permit.

这篇关于rails 4 ActiveModel::ForbiddenAttributesError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆