maeshimaの日記

メモ書きです

今週のrailscasts - Nested Model Form Part 2


先週の続き。has_manyなどでネストされたモデルを一つのフォームで扱うためのaccepts_nested_attributes_forメソッドの使い方について。
Ajaxで動的にフォーム操作をするtipsの紹介。

Railscasts - Nested Model Form Part 2

prototype.jsを使って動的にテキストフィールドを表示したり消したりしてるだけで、ajax部分にそれほど見所はなかった。気になったのは下記のコード。あんまり深掘りしてないけど、Railsのコードを読み込んでないとこのコードを発想は出てこない。感心した。

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
  end