ネストされた属性のパラメータが許可されていません 質問する

ネストされた属性のパラメータが許可されていません 質問する

オブジェクトがありBill、その中には多くのDueオブジェクトがあります。このDueオブジェクトは にも属しています。とその子をすべて 1 ページにPerson作成できるフォームが必要です。 のようなネストされた属性を使用してフォームを作成しようとしています。BillDuesこのRailscast

関連するコードは以下の通りです。

期限.rb

class Due < ActiveRecord::Base
    belongs_to :person
    belongs_to :bill
end

ビル.rb

class Bill < ActiveRecord::Base
    has_many :dues, :dependent => :destroy 
    accepts_nested_attributes_for :dues, :allow_destroy => true
end

請求書コントローラ.rb

  # GET /bills/new
  def new
      @bill = Bill.new
      3.times { @bill.dues.build }
  end

請求書/_form.html.erb

  <%= form_for(@bill) do |f| %>
    <div class="field">
        <%= f.label :company %><br />
        <%= f.text_field :company %>
    </div>
    <div class="field">
        <%= f.label :month %><br />
        <%= f.text_field :month %>
    </div>
    <div class="field">
        <%= f.label :year %><br />
        <%= f.number_field :year %>
    </div>
    <div class="actions">
        <%= f.submit %>
    </div>
    <%= f.fields_for :dues do |builder| %>
        <%= render 'due_fields', :f => builder %>
    <% end %>
  <% end %>

請求書/_due_fields.html.erb

<div>
    <%= f.label :amount, "Amount" %>        
    <%= f.text_field :amount %>
    <br>
    <%= f.label :person_id, "Renter" %>
    <%= f.text_field :person_id %>
</div>

bills_controller.rb への更新これはうまくいきます!

def bill_params 
  params
  .require(:bill)
  .permit(:company, :month, :year, dues_attributes: [:amount, :person_id]) 
end

適切なフィールドがページ上にレンダリングされ (ドロップダウンはPersonまだありませんが)、送信は成功します。ただし、子供の会費はいずれもデータベースに保存されず、サーバー ログにエラーがスローされます。

Unpermitted parameters: dues_attributes

エラーの直前に、ログに次のように表示されます。

Started POST "/bills" for 127.0.0.1 at 2013-04-10 00:16:37 -0700
Processing by BillsController#create as HTML<br>
Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"ipxBOLOjx68fwvfmsMG3FecV/q/hPqUHsluBCPN2BeU=",
 "bill"=>{"company"=>"Comcast", "month"=>"April ", 
"year"=>"2013", "dues_attributes"=>{
"0"=>{"amount"=>"30", "person_id"=>"1"}, 
"1"=>{"amount"=>"30", "person_id"=>"2"},
 "2"=>{"amount"=>"30", "person_id"=>"3"}}}, "commit"=>"Create Bill"}

Rails 4 では何か変更がありましたか?

ベストアンサー1

属性保護の処理が変更されたようで、以前はオプションだった gem の strong_parameters が Rails Core の一部になったため、(モデルの attr_accessible ではなく) コントローラでパラメータをホワイトリストに登録する必要があります。

次のようになります:

class PeopleController < ActionController::Base
  def create
    Person.create(person_params)
  end

private
  def person_params
    params.require(:person).permit(:name, :age)
  end
end

だからparams.require(:model).permit(:fields)使われるだろう

ネストされた属性の場合は次のようになります

params.require(:person).permit(:name, :age, pets_attributes: [:id, :name, :category])

詳細は以下をご覧ください。Ruby エッジ API ドキュメントそしてgithub の strong_parametersまたはここ

おすすめ記事