Rails:Selectize multiselect仅提交最后一个选择

时间:2015-02-04 19:50:36

标签: javascript jquery ruby-on-rails forms selectize.js

我有一个表单来创建一个新用户。我尝试使用gem selectize-rails允许选项添加多个相关用户:

视图/用户/ new.html.erb

<%= form_for @user, :url => users_path do |f| %>
  <select name="users" id='select-user'>
    <option value="">Select at least one user</option>
    <% User.all.each do |user| %>
      <option value="<%= user.name %>"><%= user.name %></option>
    <% end %>
  </select>
    <script type="text/javascript">
      var select = $('#select-user').selectize({
          persist: false,
          maxItems: 3,
          create: false,
          valueField: 'name',
          labelField: 'name',
          searchField: ['name'],
          render: {
              item: function(item, escape) {
                  return '<div>' +
                      (item.name ? '<span class="select-name">' + escape(item.name) + ',</span>' : '') +
                  '</div>';
              },
              option: function(item, escape) {
                  var label = item.name;
                  return '<div>' +
                      '<span class="select-label">' + escape(label) + '</span>' +
                  '</div>';
              }
          },
          preload: false,
          load: function(query, callback) {} 
      });
    </script>
  <%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>

控制器/ user_controller.rb

  def new
      @user = User.new
    end

    def create
      @user = User.new(user_params)
      if @user.save
        redirect_to root_path
      else
        redirect_to new_user_path
      end
    end

    private

      def user_params
        params.require(:user).permit(:name, :users)
      end

new.html.erb上,代码运行正常:我最多可以添加三个用户。但是当我提交它时,params["users"]只包含我添加的最后一个用户,无论我尝试添加多少用户。有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:4)

变化:

<select name="users" id='select-user'>

<select name="users" id='select-user' multiple='multiple'>

这应该让rails期望从select中获得多个值。

整个选择部分可以使用rails select helper重写。

<select name="users" id='select-user'>
  <option value="">Select at least one user</option>
  <% User.all.each do |user| %>
    <option value="<%= user.name %>"><%= user.name %></option>
  <% end %>
</select>

变为

<%= select :user, options_for_collection_for_select(User.all, :name, :name),
  { prompt: "Please select.." },
  { multiple: true } %>

有关详细信息,请参阅http://guides.rubyonrails.org/v2.3.11/form_helpers.html#making-select-boxes-with-easehttp://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html