Rails 4强参数未知参数错误

时间:2015-01-12 00:48:45

标签: ruby-on-rails strong-parameters

简单的一对多关系正在进行并在服务器日志中获取未经许可的参数。

杯子1 ---- *>联系人

params看起来像

Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ay/wRwJTr4u5Vgu5oOrk7z4RC/OfeLJdN9WXuoyU7iQ=", "cup"=>{"name"=>"cupname", "location"=>"Somewhe", "type_ids"=>"1", "contact"=>{"first_name"=>"Greg", "last_name"=>"Ander", "email"=>"email@me.com", "telephone"=>"444906398"}}, "commit"=>"Create new cup"}

cups_controller.rb

class CupsController < ApplicationController

def create
    @cup = Cup.new(cup_params)
    render nothing: true
end

private
        def cup_params
            params.require(:cup).permit(:name,:location,:type_ids,   
                :contacts_attributes => [:first_name, :last_name, :email, :telephone ])
        end

cup / new.html.erb 中 - f是杯子的主要形式

<%= f.fields_for :contacts do |contact_info| %>    
      <%= contact_info.label :first_name %><%= contact_info.text_field :first_name %>
      <%= contact_info.label :last_name %><%= contact_info.text_field :last_name %>
      <%= contact_info.label :email %><%= contact_info.email_field :email %>
      <%= contact_info.label :telephone %><%= contact_info.telephone_field :telephone %>
      <% end %>

继续获取Unpermitted parameter contact

Cup模型有accepts_nested_attributes_for :contacts

模型文件

class Cup < ActiveRecord::Base
    has_many :contacts
    has_and_belongs_to_many :types
    accepts_nested_attributes_for :contacts
end

class Contact < ActiveRecord::Base
    belongs_to :cup
end

修改

添加了更新的cup_params和控制器类。还有型号。

1 个答案:

答案 0 :(得分:2)

您需要引用contacts_attributes,而不是自己联系。

def cup_params
  params.require(:cup).permit(:name,:location,:type_ids,   
    contacts_attributes: [:first_name, :last_name, :email, :telephone ])
end