Multiplyselect在搜索后会忘记所有者的值。
进行之后,我得到了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。