理論
ネストされた属性とfields_forを非常に頻繁に使用する場合、javascriptを使用してフォームに新しい要素を追加する必要があります。
DRYの原則に従って、次のソリューションを使用することをお勧めします。 これはよく知られた手法であることは知っていますが、通常は大多数が解決策を発明します。
application_helper.rbには、すでに次のコードが追加されています。
def add_object_link(name, form, object, partial, where) html = render(:partial => partial, :locals => {:form => form}, :object => object) link_to_function name, %{ var new_object_id = new Date().getTime() ; var html = jQuery(#{html.to_json}.replace(/index_to_replace_with_js/g, new_object_id)).hide(); html.appendTo(jQuery("#{where}")).slideDown('slow'); } end
これは、javascriptを使用して新しい要素のhtmlを生成するメインヘルパーです。ここで、
名前 -リンクのタイトル
form -form_forフォームオブジェクト
object-追加される要素のオブジェクト
partial-追加される要素を表示するためにhtmlが生成するテンプレートの名前
where-ページ上のhtmlコンテナーのID
例
いくつかの特性(アンカー)を追加する必要があるルーブリック(ルーブリック)があるとします。
アプリ/モデル/ rubric.rb
class Rubric < ActiveRecord::Base has_many :anchors accepts_nested_attributes_for :anchors, :allow_destroy => true end
アプリ/モデル/ anchor.rb
class Anchor < ActiveRecord::Base belongs_to :rubric end
app / view / admin / rubrics / edit.html.haml
- form_for @rubric do |f| %h3 != add_object_link('<img src="/images/icons/add.png" />', f, Anchor.new, "anchor", "#anchors") %ul
アプリ/ビュー/管理者/ rubrics / _anchor.html.haml
- raise ArgumentError unless defined?(form) - raise ArgumentError unless defined?(anchor) %li.anchor - form.fields_for :anchors, anchor, :child_index => (anchor.new_record? ? "index_to_replace_with_js" : nil) do |anchor_form| != anchor_form.text_field :title - if anchor_form.object.new_record? %a{:href => "#", :onclick => "jQuery(this).parent('.anchor').remove(); return false;"} %img{:src => "/images/icons/delete.png"} - else != anchor_form.check_box '_destroy' != anchor_form.label '_destroy', '?'
ps私は何もふりをしません。もっと多くの人を私の信仰に変えたいと思います=)