Question

I want to call a method that updates an attribute when saved.

Here is my index.html.erb

 <% @users.each do |user| %>
<div>
    <strong><%= user.email %></strong> 
</div>
 <% if can? :update, User %>
 <%= link_to 'Make Author', User, method: :add_roles %>
 <% end %>

Below is my user_controller.rb

  def add_roles
respond_to do |format|
  if @user.update(user_params)
    user.author = true
    user.save!
    format.html { redirect_to @user, notice: 'User was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: 'edit' }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end

end

It doesn't update the attribute though. I think it is because I am not properly attaching it to the correct user. I want to current_user to update another user.

No correct solution

OTHER TIPS

I think the solution is simple, first do what avlazarov said in his comment:

In the view <%= link_to 'Make Author', "/users/#{user.id}/add_roles", method: :patch %> In the routes.rb patch '/users/:id/add_roles' => 'user#add_roles'

Or something simpler, in routes.rb:

resources :users do
  patch :add_roles, on: :member
end

then in view:

<%= link_to 'Make author', add_roles_users_path(user) %>

Then rename user_controller.rb placed in app/controllers to users_controller.rb and make sure the class name is UsersController.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top