multipleselect在继续之后伪造选定的值

时间:2016-03-10 14:10:48

标签: javascript jquery ruby-on-rails ruby jquery-select2

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

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>

1 个答案:

答案 0 :(得分:1)

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

请参阅docs here