gpt4 book ai didi

javascript - rails : Selectize multiselect only submits the last selection

转载 作者:行者123 更新时间:2023-11-30 10:07:43 25 4
gpt4 key购买 nike

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

views/users/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 %>

controllers/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"] 只包含我添加的最后一个用户,无论我尝试添加多少。有谁知道为什么会这样?

最佳答案

改变:

<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了解更多详情。

关于javascript - rails : Selectize multiselect only submits the last selection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com