Rails/Ruby select_tag 和选择不工作

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

rails select_tag 和 selected 属性有问题,因为它似乎没有传递选定的值,只有所有项目都传递给控制器。

在表单块下方的视图中,

 <div class="col-md-2">
      <div class="form-group">
      <%= label_tag 'Exportações'  %> <br/>
        <div class="input-group">
        <%= select_tag :status, options_for_select(statuses.map { |status| [status, status] }, :selected => params[:status]), :multiple => true, :prompt => 'All', :class => 'form-control shadow-sm form-control-sm'%>
        <div class="input-group-append">
        <%= link_to admin_status_export_path, class: 'btn btn-sm btn-dark ml-4', method: :post do %>
        <%= icon('fas', 'file-excel ', ' Exportaçõ') %>
        <% end %>
        </div>
        </div>
        </div>
      </div>

目前,为了识别个人状态(白名单等),在控制器中仅输出为 json,比较发送到 DB 中所有项目的内容:

 def customers_status_export
@customers = Customer.where(status_trust: %w[blacklist whitelist normal])
@status = params[:status]
if @status.present?
  @customers = @customers.where(status_trust: @status)
end
render json: @customers

When one item is selected in the view (whitelist, of which 4 are in DB, and whitelist, blacklist and normal in the select box.) we still get all the items as json, when only want for now the 4 whitelist items, so the selected param in the select_tag is not catching whitelist?

状态是从 uniq 之前对 db 的调用映射的,如果再添加更多,最好在 select_tag 中对它们进行硬编码,还是有其他影响?

(其他一切都很好,包括完成时的 csv 文件下载,这是所有项目,而不是仅列入白名单并选中的 4 个项目)

欢迎任何提示?

谢谢

ruby-on-rails select html-select
1个回答
0
投票

options_for_select 基本上输入是第一个参数的数组,第二个参数直接是它的值。

  options_for_select([ "VISA", "MasterCard" ], "MasterCard")
  # above is an array and the second parameter is the selected value

你的问题

  # if statuses is an array

  options_for_select(statuses.map { |status| status }, params[:status])

  # if statuses is a record

  options_for_select(statuses.map { |status| status.put_here_field_name }, params[:status])

编辑 2:options_from_collection_for_select

  
  options_from_collection_for_select(collection, value_method, text_method, selected = nil)
  # since you want more than one selected items I think this can help
  in controller / other place
  @selected_reason_array = ['abc', 'def']

  options_from_collection_for_select(@reasons, "id", "text", selected:  @selected_reason_array)
  # pay attentions to second and third parameters
  # @reasons are your records that automatically will be looped
© www.soinside.com 2019 - 2024. All rights reserved.