您好我有一个角色应用,用户可以拥有多个角色。我正在使用Roles Model Gem。如下所示:
4.2.5@2.2.4 (main)> User.valid_roles
=> [
[0] :admin,
[1] :report_writer,
[2] :candidate,
[3] :client_contact
]
我想要一个可以为用户选择多个角色的复选框表单。我已经尝试了一个小时但无法弄明白。有人可以帮忙吗?
这是表格
%h1 Edit User
= form_for @user, url: admin_user_path(@user) do |f|
.form-group
= f.label :first_name
= f.text_field :first_name
.form-group
= f.label :last_name
= f.text_field :last_name
.form-group
= f.label :email
= f.text_field :email
.form-group
= f.label :password
= f.password_field :password
.form-actions
= link_to "Cancel", admin_users_path, class: "btn btn-grey"
= f.submit class: "btn btn-primary pull-right"
答案 0 :(得分:1)
Haven't used role_model gem, but looking at docs, the following should work:
<%= form_for @user, url: admin_user_path(@user) do |f| %>
...
<div class='form-group'>
<% User.valid_roles.each do |valid_role| %>
<div>
<%= valid_role.humanize %>
<%= f.check_box :roles, multiple: true, valid_role %>
</div>
<% end %>
</div>
...
<% end %>
After submitting the form, your server should receive the following params (example when checked both 'admin' and 'client_contact'):
{
user: {
first_name: '...',
last_name: '...',
email: '...',
password: '...',
roles: [
'admin',
'client_contact'
]
}
}
Do not forget to include roles: []
to strong params. Example below:
users_controller.rb
def create
@user = User.new(user_params)
...
end
...
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, roles: [])
end