0

ネストされたモデルからデータベースにデータを追加できません。

Monster モデルと次の関係を持つ Photo モデルがあります。ネストされたモンスターのフォームを追加および削除できますが、写真を更新するときに新しいモンスター オブジェクトを実際に追加する方法がわかりません。これはhttp://railscasts.com/episodes/196-nested-model-form-revisedの例からの 1 つのネストされたレベル フォームに基づいており、基本的に調査 - 質問の関係が示されています。

class Photo < ActiveRecord::Base
  attr_accessible :title, :monsters_attributes

  has_and_belongs_to_many :monsters

  accepts_nested_attributes_for :monsters, allow_destroy: true
end

class Monster < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :selected

  has_and_belongs_to_many :photos
end

問題は私の photos_controller にあると確信しており、写真フォームを更新するときに送信されたパラメーターの使用方法をよく理解していません。モンスターが 2 体いる編集写真フォームを送信すると、次の params ハッシュが得られます。1 つ目は既に関連付けられており、2 つ目は [モンスターを追加] リンクをクリックして名前と姓を入力し、フォームを送信して宣言しようとしています。

「モンスターを追加」リンクは、写真の _form.html.erb ファイルで定義されており、部分を使用してフィールドをレンダリングしています。ヘルパー関数は application_helper.rb で宣言されています。

_form.html.erb

…
    <!-- this uses the _monster_fields partial -->
    <%= f.fields_for :monsters do |builder| %>
      <%= render 'monster_fields', f: builder %>
    <% end %>        

  </table>

  <%= link_to_add_fields "Add Monster", f, :monsters %>
...

application_helper.rb

module ApplicationHelper

  def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new  # make instance of monster association record, Monster.new
    id = new_object.object_id                          # get id of new monster object, id = Monster.new.object_id

    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize + "_fields", f: builder)    # render partial _monster_fields.html.erb
    end

    link_to(name, "#", class: "add_fields", data: {id: id, fields: fields.gsub("\n", '&#xA')}) # returns a link    
  end
end

表示する写真の編集 (更新) から表示されるパラメータ:

{
"utf8"=>"✓", 
"_method"=>"put", 
"authenticity_token"=>"8dYkFrzdkulBv8YrZCHU2wfFh4v5LQc9q/JWPmsbDkc=", 
"photo"=>{"title"=>"Family Gathering", 
    "monsters_attributes"=>{
    "0"=>{"first_name"=>"Franken", "last_name"=>"Stein", "_destroy"=>"false", "id"=>"1"}, 
    "1358291763102"=>{"first_name"=>"Ware", "last_name"=>"Wolf", "_destroy"=>"false"}
    }, 
    "monster_ids"=>"1"
   }, 
"commit"=>"Update Photo", 
"action"=>"update", 
"controller"=>"photos", 
"id"=>"1"
}

私の applcation.js ファイルでは、フィールドの追加と削除を処理する方法を定義します。.add_fields では、この例では新しく作成したオブジェクトの ID を使用していますが、新しく作成したモンスターをモンスター テーブルに保存する方法がわかりません。

アプリケーション.js

$(document).ready(function() {

  $('form').on('click', '.remove_fields', function(event) {
    $(this).prev('input[type=hidden]').val('1');
    $(this).closest('tr').hide();
    event.preventDefault();
  });

  $('form').on('click', '.add_fields', function(event) {
    time = new Date().getTime();
    regexp = new RegExp($(this).data('id'), 'g');
    $(this).before($(this).data('fields').replace(regexp, time))    
    event.preventDefault();
  });

});

全体として、これは非常に単純なプロセスですが、実際に写真編集ビューから新しいモンスターを保存する (新しいアクティブ レコード オブジェクトを作成する) 場合、さらに先に進む方法がわかりません。

多対多の関係を使用すると問題が発生する可能性はありますか?

railscasts の例は良いですが、そこまでは行きません。誰かの助けに感謝します。

http://railscasts.com/episodes/196-nested-model-form-revised

2013 年 1 月 16 日更新: 私の params ハッシュとエラー

ActiveModel::MassAssignmentSecurity::PhotosController#update のエラー

保護された属性を一括割り当てできません:monster_ids

app/controllers/photos_controller.rb:76:block in update' app/controllers/photos_controller.rb:75:in更新中'

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"1l62Sged52hnEHQoj0WPf/asRjcIpIKBBzsb7gVDRm0=",
 "photo"=>{"title"=>"Family Gathering",
 "monsters_attributes"=>{"0"=>{"first_name"=>"Franken",
 "last_name"=>"Stein",
 "_destroy"=>"false",
 "id"=>"1"},
 "1358356969634"=>{"first_name"=>"Scary",
 "last_name"=>"Frank",
 "_destroy"=>"false"}},
 "monster_ids"=>"1"},
 "commit"=>"Update Photo",
 "id"=>"1"}
4

1 に答える 1

0

ネストされた属性の利点は、コントローラー コードへの影響が存在しないことです。あなたはやり続けることができます

photo.update_attributes params[:photo]

また、モンスターは適宜更新および削除されます:photo.monsters_attributes=からのデータを使用して update_attributes によって呼び出されparams[:photo][:monsters_attributes]ます。呼び出しaccepts_nested_attributes_forにより、(とりわけ)適切なmonsters_attributes=メソッドが作成されます

于 2013-01-16T14:51:16.857 に答える