没有强参数的ActiveModel :: ForbiddenAttributesError

时间:2015-10-02 07:28:18

标签: ruby-on-rails

所以我得到了以下哈希:

hash = {
  "role"=>"#", 
  "city"=>"#", 
  "listing_attributes"=>
    {
      "desks_attributes"=>
        {
          "0"=>{"quantity_available"=>"#"}
        }
    },
  "username"=>"#", 
  "email"=>"#", 
  "fullname"=>"#", 
  "password"=>"#", 
  "password_confirmation"=>"#", 
  "terms"=>"#"
}

我正在尝试构建一个User模型对象:

User.new(
  :username => hash[:username],
  :fullname => hash[:fullname],
  :first_name => hash[:first_name],
  :last_name => hash[:last_name],
  :email => hash[:email],
  :password => hash[:password],
  :password_confirmation => hash[:password_confirmation],
  :role => hash[:role],
  :city => hash[:city],
  :terms => hash[:terms],
  :listing_attributes => hash[:listing_attributes]
)

它似乎返回以下ActiveModel :: ForbiddenAttributesError,我知道这个错误可以在使用强参数时提高它的头部但我不能在不使用强参数的情况下锻炼如何绕过它?或者有一种方法可以将强参数合并到此代码中吗?

为了记录,我有以下型号:

class Desk < ActiveRecord::Base
  belongs_to :listing
  has_one :user, through:  :listing
end

class Listing < ActiveRecord::Base
  belongs_to :user
  has_many :desks, dependent: :destroy

  accepts_nested_attributes_for :user, :desks
end

class User < ActiveRecord::Base
  has_one :listing, dependent: :destroy
  has_many :desks, :through => :listing
  accepts_nested_attributes_for :listing
end

我已经为我的强参数设置了以下内容:

params.require(:user).permit(:username, :fullname, :first_name, :last_name,:email, :password, :password_confirmation,:password_digest, :role, :city, :terms,listing_attributes: [:company_name, :address, :post_code, :user_id, :city, :latitude, :longitude, desks_attributes: [:quantity_available]])

1 个答案:

答案 0 :(得分:0)

您是否允许控制器中的所有参数?

例如:

private
  def user_params
    params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
  end