D
D
dexdev2014-01-26 00:49:18
Ruby on Rails
dexdev, 2014-01-26 00:49:18

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

models/users_role.rb
belongs_to :user
belongs_to :role

models/role.rb
has_many :users_roles
has_many :users, through: :users_roles

In the controller I specify:
controllers/users_controller.rb
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

And in the view I make the following form:
views/users/edit.html.erb
<%= 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 %>

But it doesn't work, I can't figure out how to pass attributes to create the required fields in the users_role database.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dexdev, 2014-01-26
@AdilA

and the joke was that it was stupid to add params.require(:user).permit(:name, roles_attributes: [ :user_id, :role_id]) instead of
params.require
(:user).permit(:name, : role_ids => [])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question