我有一个表单,其中有一个 fields_for
,其中包含循环的多个记录。每条记录都使用一个打开的模式,然后用于添加表单条目。我的问题是,为了打开模式,我需要使用唯一标识符。在创建“主”表单记录之前,我没有可用作唯一标识符的 ID。我尝试使用初始化版本,它是唯一的,但它不会打开模型。我假设是因为初始化的记录中有一个 #
...
创建记录时我可以使用此功能,因为这样我就可以使用 ID。但这是我的初始化记录问题:
我的 Controller :
@shop_product = ShopProduct.find_or_initialize_by()
表格总结:
<%= form_for @shop_product do |f| %>
<%= f.fields_for :shop_product_print_files do |ff| %>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal-<%= "#{ff.object.print_location.id}" %>_<%= "#{@shop_product}" %>" id="printLocationId_<%= "#{ff.object.print_location.id}" %>(<%="#{ff.object.print_location.id}"%>)">
Choose Image
</button>
<div class="modal fade" id="myModal-<%= "#{ff.object.print_location.id}" %>_<%= "#{@shop_product}" %>" tabindex="-1" role="dialog" data-keyboard="false">
</div>
<% end %>
<%= f.submit "Sync" %>
<% end %>
这意味着:http://jsfiddle.net/a01h6rz7
^这显示了按钮和模态之间的关系。模态有很多,所以我需要一个独特的模态,以便模态打开正确的关联。
当我创建记录时,我可以使用@shop_product.id
并且它会起作用。有没有办法在新产品上使用 @shop_product
来获取有效的唯一标识符?
我标记 javascript 是为了以防万一有想法或方法可以根据 @shop_product
初始化创建唯一标识符。如果您想帮助解决更多信息,请告诉我
最佳答案
试试这个代码
<%= form_for @shop_product do |f| %>
<% shop_product_id = @shop_product.object_id %>
<%= f.fields_for :shop_product_print_files do |ff| %>
<% print_location_id = ff.object.print_location.id%>
<button
type="button"
class="btn btn-primary"
data-toggle="modal"
data-target="#myModal-<%= print_location_id %>_<%= shop_product_id %>"
id="printLocationId_<%= print_location_id %>(<%= print_location_id %>)"
>
Choose Image
</button>
<div
class="modal fade"
id="myModal-<%= print_location_id %>_<%= shop_product_id %>"
tabindex="-1"
role="dialog"
data-keyboard="false">
</div>
<% end %>
<%= f.submit "Sync" %>
<% end %>
- 首先不要使用
@shop_product
因为那是一个对象。如果您需要引用但还没有 ID,object_id
将为您提供一个唯一的标识符。 - 如果您需要一次又一次地创建/使用相同的东西,您可以在模态中创建一个方法,或者提取 block 内变量中的值。
- 如果您不需要
print_location
那么你不需要做ff.objec.print_location.id
它将查询print_location
。而是使用print_location_id
. - 不要像这样使用不必要的字符串插值
<%= "#{ff.object.print_location.id}" %>
而只是简单的 erb 代码,例如<%= ff.object.print_location.id %>
关于javascript - 如何使用初始化的模型作为模式打开的唯一标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59810569/