0

我正在努力处理一些动态插入字段的嵌套表单。我的代码基于 Ryan Bates 很棒的 railscasts。不过我的问题是我需要将“添加字段”按钮移到嵌套表单之外。这会导致问题,因为我无权访问生成表单所需的某些对象。

在下面的代码中,添加/删除按钮位于同一位置。我可以更改 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
4

1 回答 1

0

通过将最后一个循环对象存储到一个变量并在循环外使用它来解决。

(...) -thisvar = fl

-link_to_add_fields "添加新级别", f, :fund_levels, thisvar, i+1, ad

于 2012-11-03T03:13:16.613 回答