2013-07-07 116 views
1
def link_to_add_nested_fields(name, f, association, klasss, type) 
    new_object = f.object.send(association).klass.new 
    id = new_object.object_id 
    field = f.fields_for(association, new_object, child_index: id) do |builder| 
     render(association.to_s.singularize + "_#{type}", f: builder) 
    end 
    link_to(name, '#', class: klasss, data: {id: id, type: field.gsub("\n", "")}) 
    end 

我想自定義一塊幫手代碼我從這裏得到http://railscasts.com/episodes/196-nested-model-form-revised,但我有問題的類型參數。這個助手正在使用的一個例子;嵌套域輔助方法

<%= link_to_add_nested_fields "Add custom field", f, :fields, "add_fields","fields" %> 

問題是肯定與類型參數,有沒有人知道我可以解決這個問題? 謝謝

回答

1

我已經看到這個轉換,這似乎並不是處理嵌套屬性的「添加更多」鏈接的最佳解決方案。

基本上,accept_nested_attributes的工作方式在這裏是關鍵。

在你controller

parent.child.build 

只有一次建立它的初始視圖。這將使該字段最初出現在頁面重新加載上。

在你.erb template

<% parent.children.each do |child| %> 
<div class="child_fields"> 
    <%= render "the child fields partial" %> 
</div> 
<% end %> 
<%= link_to "Add More", "#", class: "add_more_link" %> 
<% javascript_include_tag "js_file_to_handle_add_more_link" %> 

在你"js_file_to_handle_add_more_link.js"

首先,算上現有的子場使用:

$('.child_fields').size(); 

現在,id作爲創建HTML領域

parent_children_attributes_" + count + "_attribute_name" 

和名稱:

"parent[children_attributes]["+ count +"][attribute_name]" 

每一組子字段應該有一個獨特的價值計數。此外,這裏的父母是單數,而孩子是複數。

而就是這樣。

現在當提交表單時,軌道會自動爲每一個它是由accepts_nested_atributes格式識別唯一

+0

感謝這個救子對象,我會嘗試一下在我的下一個項目,但現在我有很多代碼(包括紅寶石和JavaScript)投資於這種方法,使它適合我的需求:(你知道我可以如何將字符串的類型參數轉換爲純文本嗎?或者更好的還有散列鍵? – Skyalchemist

+0

你可以解釋一下這一點嗎 – Nerve

+0

我傳遞字符串「字段」的類型參數,所以在倒數第二行(link_to),數據是現在;數據:{id:id,「字段「:field.gsub(」\ n「,」「)}因爲type是一個字符串,我想要的是data:{id:id,fields:field.gsub(」\ n「,」「)}。不是「領域」,你會得到什麼? – Skyalchemist