我有一个表单来创建一个新用户。我尝试使用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"]
只包含我添加的最后一个用户,无论我尝试添加多少用户。有谁知道为什么会这样?
答案 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-ease和http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html。