2016-11-17 17 views
0

4つの関連モデルでform_forを作成しました。私はネストされたfields_forを作成し、以下のコードで動的に追加することができます。フォームは私が 'edit'メソッドを呼び出すと機能しますが、以下のメソッドを使って新しいデータを追加すると、fields_forは空のままで、表示されません。空の関連付けfields_forコンテンツがjqueryによって動的に追加された場合

def link_to_add_fields(name, f, association) 
    new_object = f.object.send(association).klass.new 
    id = new_object.object_id 
    fields = f.fields_for(association, new_object, child_index: id) do |builder| 
     render(association.to_s.singularize + "_fields", f: builder) 
    end 
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")}) 
    end 

これは、モデルの1つのフォームのみを追加したい場合に有効です。しかし、text_fieldsのためにfields_forがネストされたfields_forを持つ追加されたコンテンツが作成されない場合。私の意見では、私は団体を構築していないからです。これを行うにはどうすればこの方法を修正できますか?

答えて

0

私はnilとしてchild_indexを設定する(Itay Grudev's blog postに基づいて)非常に類似した方法を、持っていた後、(多くのレコードが同じidを持つそれらを避けて追加することができるように)タイムスタンプでそれを置き換えるためにjQueryのを使用します。だから、

、私が持っている私のapplication_helper.rbファイル内:

def link_to_add_fields(name = nil, f = nil, association = nil, options = nil, html_options = nil, &block) 
    f, association, options, html_options = name, f, association, options if block_given? 
    options = {} if options.nil? 
    html_options = {} if html_options.nil? 

    if options.include? :locals 
     locals = options[:locals] 
    else 
     locals = { } 
    end 
    if options.include? :partial 
     partial = options[:partial] 
    else 
     partial = association.to_s.singularize + '_fields' 
    end 

    new_object = f.object.class.reflect_on_association(association).klass.new 
    fields = f.fields_for(association, new_object, child_index: nil) do |builder| 
     render(partial, locals.merge!(fields: builder)) 
    end 

    html_options['data-form-prepend'] = raw CGI::escapeHTML(fields) 
    html_options['href'] = '#' 

    content_tag(:a, name, html_options, &block) 

エンド

そして私は自分の名前を置き換え、私は新しく追加されたフィールドを見つけているdynamic_tables.js.coffeeと呼ばれるCoffeeScriptのファイルを追加しましたタイムスタンプ(それらはすべてグループとしてインデックス付けされているので)、ターゲット(テーブルの一番下に追加した隠し要素で、prepend_targetとマークしたもの)にフォームを追加します。だから私は持っている:

$('[data-form-prepend]').click (e) -> 
    target = $($(this).attr('prepend_target')) 
    obj = $($(this).attr('data-form-prepend')) 
    current_time = (new Date).getTime() 
    obj.find('input, select, textarea').each -> 
     $(this).attr 'name', -> 
     $(this).attr('name').replace 0, current_time 
     return 
    obj.insertBefore target 
    false 

それはトリックを行う必要があります。お役に立てれば。

関連する問題