【问题标题】:Rails: Dependent Fields inside a formRails:表单内的依赖字段
【发布时间】:2015-12-09 11:09:12
【问题描述】:

我想在我的应用程序中实现依赖字段。为此,我使用了dependent-fields-rails gem。我已经用this tutorial 设置了所有内容。好东西:它有效。有点儿。在我的品牌模型中,我列出了阿迪达斯、耐克等品牌...

现在我的两个挑战:

  1. 我不知道必须在data-option-value=" " 字段中填写什么,因为如果完全选择了品牌而不是特定品牌,我想显示类别的选择表单。如果我在data-option-value="Adidas" 之类的字段(硬编码)中输入了一个值,那么只有在我从品牌下拉列表中选择了“阿迪达斯”时,才会出现 category_select 表单。
  2. 我只想显示在步骤 1 中选择的品牌的匹配类别。我的组模型还包含品牌记录,因此我可以将类别与品牌匹配。

为了更清楚一点:

  • 品牌模型包含阿迪达斯、耐克等公司...
  • 组模型包含鞋类、衬衫等类别...

这是我得到的:

<div class="form-group">
  <%= f.label :brand %>
  <%= f.select(:brand, Brand.pluck(:company).uniq, {prompt:true}, {class: 'form-control'}) %>
</div>
<div class="form-group js-dependent-fields" data-select-id='warehouse_brand' data-option-value="Adidas">
  <%= f.label :category %>
  <%= f.collection_select(:category, Group.all, :brand, :name1, {prompt:true}, {class: 'form-control'}) %>
</div>

有什么想法吗?提前非常感谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我假设一个品牌有很多组。如果您不想使用硬编码值,请将 js-dependent-fields 放入循环中,如下面的代码所示。

    <div class="form-group">
      <%= f.label :brand %>
      <%= f.select(:brand, Brand.pluck(:company).uniq, {prompt:true}, {class: 'form-control'}) %>
    </div>
    <% Brand.all.each do |b| %>
      <div class="form-group js-dependent-fields" data-option-value= "#{b.company}" data-select-id="warehouse_brand">
        <%= f.label :category %>
        <%= f.collection_select(:category, Group.where(brand_id: "#{b.id}"), :brand, :name1, {prompt:true}, {class: 'form-control'}) %>
      </div>
    <% end %>
    

    要仅显示匹配的类别,您可以编写一个查询,选择与代码相关的品牌

    Group.where(brand_id: "#{b.id}")
    

    【讨论】:

    • 不起作用。 HTML 输出为 "data-option-value="#{b.company}""
    【解决方案2】:

    这确实有效:

    <div class="form-group">
      <%= f.label :brand %>
      <%= f.select(:brand, Brand.pluck(:company).uniq, {prompt:true}, {class: 'form-control'}) %>
    </div>
    <% Brand.all.each do |b| %>
      <div class="form-group js-dependent-fields" data-option-value="<%= b.company %>" data-select-id="warehouse_brand">
        <%= f.label :category %>
        <%= f.collection_select(:category, Group.where(brand: b.company), :brand, :name1, {prompt:true}, {class: 'form-control'}) %>
      </div>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 2016-05-16
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多