Answer the question
In order to leave comments, you need to log in
How to add roles in a rails 4 application?
Faced a problem, I can't figure out how to change roles for users. You need to be able to change the role of users at any time:
So, cancan, devise, rails 4 ruby 2.0.
models/user.rb
has_many :users_roles, dependent: :destroy
has_many :roles, through: :users_roles
belongs_to :user
belongs_to :role
has_many :users_roles
has_many :users, through: :users_roles
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to @user
end
end
private
def user_params
params.require(:user).permit(:name, roles_attributes: [ :user_id, :role_id])
end
<%= form_for (@user) do |f| %>
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= hidden_field_tag "user[role_ids][]", nil %>
<% Role.all.each do |role| %>
<%= check_box_tag "user[role_ids][]", role.id, @user.role_ids.include?(role.id), id: dom_id(role) %>
<%= label_tag dom_id(role), role.name %><br>
<% end %>
<%= f.submit %>
<% end %>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question