How to set user as admin [rails]

I am trying to set a user as administrator and this is the code I have written so far:

app / controllers / users_controller.rb

class UsersController < ApplicationController

  before_action :admin_user,     only: [:destroy]
  ..
  ..
  def admin_user
    redirect_to(root_url) unless current_user && current_user.admin?
  end

end

      

db /seeds.rb

User.create!(name:  "admin",
             surname: "admin",
             email: "admin@1.it",
             password:              "password",
             password_confirmation: "password",
             admin: true)

      

So when I create a user with these specs, it doesn't work either: by typing "localhost: 3000 / users" it redirects me to root_url, not the user page. Can anyone help me? what is wrong with this code? Thank you for your help!

+3


source to share


3 answers


OK, this is how I set up my admin:

  • migrate to add a logical admin table for users. it should look something like this.
class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: false
  end
end

      



  1. In the controller of the items you want to restrict as an administrator, write a method that looks something like this.
def require_admin
     if !current_user.admin?
           redirect_to benefits_path
     end
end

      

  1. At the top of this controller, write your before_action file

  2. rails console user to switch one of the users from admin false to admin true

  3. check administrator rights

+1


source


Please read the Rolify gem.



With this gem, you can define different roles for different users and validate users as roles are very easy too.

0


source


Use before_filter well if using rails3.

before_filter :admin_user,     only: [:index]

      

0


source







All Articles