从Rails 3.0(原型).js.rjs文件转换为Rails 4(jQuery)后,我无法使用此代码.js.erb
永远不会执行第$("#subcategory_0").html("<p>prova2</p>");
行
Old File,.js.rjs:
if @subcategories
@expense=Expense.new
new_expense_detail=@expense.expense_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%>
<%new_expense_detail=@expense.expense_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 :(得分: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_<%=@child_index%>_subcategory_id").empty();
$("#expense_expense_details_attributes_<%=@child_index%>_subcategory_id").append("<%=j options%>");
<%end%>
尽管我不喜欢这样:expense_expense_details_attributes_<%=@child_index%>_subcategory_id
答案 1 :(得分:0)
在fields_for块中使用实例变量,并将其传递给部分: - &gt; @builder
在js.erb
中<%
@expense=Expense.new
new_expense_detail=@expense.expense_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_<%=@child_index%>").html("<%= escape_javascript(render(partial: 'select_costcenter', locals: {f: @builder,child_index: @child_index}))%>");