【问题标题】:How can I use an initialized model to use as a unique identifier for modal opening?如何使用初始化模型作为模态打开的唯一标识符?
【发布时间】:2020-01-19 13:41:56
【问题描述】:

我有一个表单,它有一个fields_for,其中包含多个循环的记录。每条记录都使用一个打开的模式,然后用于添加表单条目。我的问题是,为了打开模式,我需要使用唯一标识符。在创建“主”表单记录之前,我没有可用作唯一标识符的 ID。我尝试使用初始化版本,这是唯一的,但它不会打开模型。我假设是因为初始化的记录中有一个#...

创建记录时我可以使用此功能,因为这样我就可以使用该 ID。但这是我的初始化记录问题:

我的控制器:

@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,它会起作用。有什么方法可以在 new 上使用 @shop_product 来获得一个可以工作的唯一标识符?

我正在标记 javascript,以防万一有想法或方法可以根据 @shop_product 初始化创建唯一标识符。如果您想帮助解决任何更多信息,请告诉我

【问题讨论】:

  • 除了创建唯一ID的方法外,我只能想到先创建记录,然后再添加属性并为其设置状态。

标签: javascript ruby-on-rails ruby


【解决方案1】:

试试这个代码

<%= 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 %>
  1. 首先不要使用@shop_product,因为那是一个对象。如果您需要参考但它还没有 ID,object_id 将为您提供一个唯一标识符。
  2. 如果您需要一次又一次地创建/使用相同的东西,您可以在模态中创建一个方法,或者在块内的变量中提取值。
  3. 如果您不需要print_location,那么您不需要执行ff.objec.print_location.id,它将查询print_location。请改用print_location_id
  4. 不要使用像 &lt;%= "#{ff.object.print_location.id}" %&gt; 这样不必要的字符串插值,而只需使用简单的 erb 代码,如 &lt;%= ff.object.print_location.id %&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2023-03-20
    • 2023-03-09
    相关资源
    最近更新 更多