2012-11-03 134 views
0

我正在努力使用一些動態插入字段的嵌套表單。我將我的代碼基於Ryan Bates偉大的railscasts。我的問題是,我需要將我的「添加字段」按鈕移出嵌套窗體。這會導致問題,因爲我無法訪問生成表單所需的一些對象。RoR:嵌套表單和動態字段

在下面的代碼中,添加/刪除按鈕位於相同的位置。我可以更改if語句來執行此操作,但我無法移動f.simple_fields_for:fund_levels循環外的添加字段按鈕。

任何建議乾淨的方式做到這一點?

視圖

 = f.simple_fields_for :fund_levels do |fl| 
     - fl.object.id ? headerappend = fl.object.id : headerappend = "#{i}-notset" 
     %div{id: "flheader-#{headerappend}"} 
     %div 
      = link_to "Sponsor levels", "#", :class => "show_hide", :id => "initiator1_fl#{i}", :style=>"margin-bottom:2px;", :onclick=>"return false" 
     %div{:class => "slidingDiv #{fund_levels_last?(i, @fund_level_count) ? "shown": "hidd" } whitebg leftadj", :id=>"body_fl#{i}", :style=>"width:100%;" } 

      = render :partial => 'fund_level_fields', :locals => {:fl => fl, :ad => ad, :i => i, :f => f} 
      %div{:style => "float: right; padding: 20px 20px 20px 0"} 
      = fund_levels_last?(i, @fund_level_count) ? (link_to_add_fields "add new level", f, :fund_levels, fl, i+1, ad) : (link_to "remove", accounts_ad_fund_level_path(ad, fl.object.id), {:class => 'button orange sm', :method => :delete, :remote => true, :confirm => t('q.are_you_sure')}) 
     - i += 1 
    %div#newfields 
     - # THE BUTTON SHOULD GO HERE if it is an ADD FIELDS (remove btn should stay above) 

由最後循環對象存儲到一個變量,並使用該外循環解決了application_helper文件

def link_to_add_fields(name, f, association, sublevel, counter, parent) 

    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, :fl => sublevel, :i => counter, :ad => parent) #fl, i, ad 
    end 

    # this bit is required because of some bugs in haml 
    fields.gsub!(/\<haml\:newline\/\>/, '').html_safe 

    link_to name, '#', :id => "#{name}|-|#{association}|-|#{fields}", :class => "addfields", :onclick => "return false" 
    end 

回答

0

(...)-thisvar = FL

-link_to_add_fields 「添加新的水平」,F:fund_levels,thisvar,+ 1,廣告