2014-01-29 22 views
0

從Rails 3.0(原型).js.rjs文件轉換爲Rails 4(jQuery).js.erb後,我無法使用此代碼fields_for helper在js.erb轉換後無法在.js.rjs中工作

$("#subcategory_0").html("<p>prova2</p>");永遠不會執行

舊文件,.js.rjs:

if @subcategories 
    @expense=Expense.new 
    [email protected]_details.build 
    form_for(@expense) do |f| 
     f.fields_for(:expense_details,new_expense_detail,:child_index=>@child_index) do |builder| 
      page.replace_html "subcategory_#{@child_index}", :partial => "expenses/subcategory", :locals=>{:f=>builder,:child_index=>@child_index} 
     end 
    end 
end 

現在,轉換後jQuery的(和Rails 4), 「prova1」 顯示,但「prova2 「不。 而且,我不知道爲什麼

$("#subcategory_0").html("<p>prova1</p>"); 
<%if @subcategories %> 
    <%@expense=Expense.new%> 
    <%[email protected]_details.build%> 
    <%form_for(@expense) do |f| %> 

    <%f.fields_for(:expense_details,new_expense_detail,:child_index=>@child_index) do |builder|%> 

     // --- This line is not executed --- // 
     $("#subcategory_0").html("<p>prova2</p>"); 

    <%end%> 
    <%end%> 
<%end%> 

非常感謝,我想這是一個愚蠢的問題,但不能發現js.erb文件的例子。 (對不起我的英語水平)

+0

在'form_for'和'f.fields_for'之前,它應該是'<%='而不是'<%',我想。 – JPG

+0

我已經嘗試過,並沒有工作。 –

回答

0

我已經找到了大刀闊斧的解決我的問題

所有這些傭工(的form_for和fields_for)在那裏重現collecion_select和其所有屬性,模式和一對多的關係。沒有硬編碼選擇的對象名稱...等

現在我只通過的JavaScript(jQuery的)和options_from_collection_for_select改變選擇選項

<%if @subcategories %> 

    <% options=options_from_collection_for_select(@subcategories, :id, :name) %> 

    $("#expense_expense_details_attributes_<%[email protected]_index%>_subcategory_id").empty(); 
    $("#expense_expense_details_attributes_<%[email protected]_index%>_subcategory_id").append("<%=j options%>"); 

<%end%> 

eventhough我不喜歡這樣的:expense_expense_details_attributes_<%[email protected]_index%>_subcategory_id

0

在fields_for塊中使用實例變量,並將其傳遞給部分: - >@builder

in js.erb

<% 
    @expense=Expense.new 
    [email protected]_details.build 
    form_for(@expense) do |f| 
    f.fields_for(:expense_details,new_expense_detail,:child_index=>@child_index) do |builder| 
     @builder=builder # <<--- New line compared js.rjs 
    end 
    end 
%> 

$("#cost_center_group_<%[email protected]_index%>").html("<%= escape_javascript(render(partial: 'select_costcenter', locals: {f: @builder,child_index: @child_index}))%>");