将空行添加到基于Ajax的选择框

问题描述 投票:0回答:1

我有一组使用一些Ajax魔法填充的选择框。 Ajax使用正确的数据加载选择框,但是我在组合框的顶部添加一个空行时遇到了问题。由于集合没有空白,因此选择框也没有。

以下是我的控制器的更新部分:

  def update_select
    @areas = Area.where("product_type_id = ?", params[:product_type_id])
    @products = Product.where("product_type_id = ? AND active = 't'", params[:product_type_id])
    @accessories = Product.where("product_type_id = ? AND active = 't' AND accessory = 't'", params[:product_type_id])
    respond_to do |format|
      format.js
    end
  end

以下是使用更新呈现的内容:

$("#area_select").empty().append("<%= escape_javascript(render(partial: "select_boxes/area", collection: @areas)) %>")
$("#product_select").empty().append("<%= escape_javascript(render(partial: "select_boxes/product", collection: @products)) %>")
$("#accessory_select").empty().append("<%= escape_javascript(render(partial: "select_boxes/accessory", collection: @accessories)) %>")

这是选择框的部分之一(它们都是三个基本相同)

<option value="<%= accessory.id %>"><%= accessory.product_number %></option>

这是实际显示表单字段的部分:

<tr class="details_row nested-fields">
  <td><%= f.select :area_id, options_for_select(@areas.collect {|c| [ c.area_name, c.id ] }, f.object.area_id), {include_blank: true}, {:id => 'area_select', :class => 'form-control'} %></td>
  <td><%= f.select :product_id, options_for_select(@products.collect {|p| [ p.product_number, p.id ] }, f.object.product_id), {include_blank: true}, {:id => 'product_select', :class => 'form-control'} %></td>
  <td><%= f.number_field :quantity, class: 'form-control', "min" => 1 %></td>
  <td><%= f.select :accessory_id, options_for_select(@accessories.collect {|p| [ p.product_number, p.id ] }, f.object.product_id), {include_blank: true}, {:id => 'accessory_select', :class => 'form-control'} %></td>
  <td><%= f.text_field :notes, class: 'form-control' %></td>
  <td><%= link_to_remove_association '<i class="fa fa-trash"></i>'.html_safe, f %></td>
</tr>

在更新选择框之前,是否有一种简单的方法可以在集合中添加空白?或者有部分方法可以在部分中执行此操作吗?我在实际表单中包含了“include_blank:true”,但是当通过Ajax更新选择框时必须忽略它。

jquery ruby-on-rails ajax ruby-on-rails-4 rails-activerecord
1个回答
0
投票

我能够使用我在documentation中发现的部分计数器来解决这个问题......所有地方...... =)

<% if accessory_counter == 0 %>
  <option value=""></option>
  <option value="<%= accessory.id %>"><%= accessory.product_number %></option>
<% else %>
  <option value="<%= accessory.id %>"><%= accessory.product_number %></option>
<% end %>
© www.soinside.com 2019 - 2024. All rights reserved.