多项选择在继续后忘记了选定的值

multipleselect is forgeting selected values after proceed

Multipleselect 在搜索后忘记了所有者的值。 继续后,我得到了 params[:search] 和 params[:owners],但只填写了搜索输入。这是我的代码。

def index
 @all_owners = Owner.select('distinct name').pluck(:name)
 @animal = Animal.search(params[:search])
 @animal = @animals.joins(:owners).where("owners.name IN (?) ", params[:owners].present? ? params[:owners] : @owners)
end

#------------------------------------------

<%= form_tag animals_path, :method => 'get' do %>
 <%= text_field_tag :search, params[:search]%>
 <%= select_tag :owners, options_for_select(@all_owners),id: "multiselect-id", multiple: true %>
<%= submit_tag "Search", :name => nil  %>
<% end %>

<% @aminals.each do |animal| %>
 <%= animal.name %>
 <%= animal.owners.map(&:name).join(', ') %>
<% end %>

<script type="text/javascript">
 $(document).ready(function() {
    $('#multiselect-id').select2();
 });
</script>

您忘记在 select_tag 中指定当前选定的值。这是完成的,例如通过 options_for_select 助手的第二个参数,即类似:options_for_select(@all_owners, params[:owners] || @owners).

参见docs here