简体   繁体   中英

how to add admin with devise in ROR

I am using devise gem and i wanna to create admin

rails g migration add_admin_to_user

in the db

 def change
    add_column :users, :admin , :boolean , {default: false}
  end

def user

def admin?
    user=User.create(email: "info@presale.ca",password: "12345678")
    user.admin=true
    user
    user.save
    admin
  end
end

in the index page

<% if current_user && current_user.admin? %>
<% end %>

theres something wrong in the def user how to fix it please?

Because you already have a boolean :admin attribute on your User model, there's a default admin? method out of the box. If you call something like User.find(1).admin? it will return true or false based on your value in your db - so you probably don't want to override this.

Define a new method in your User model to assign the admin attribute.

def make_admin!
  self.update_attribute(:admin, true)
end

Now you can call User.find(1).make_admin! in your controller, or in rails console, or wherever you have a User instance.

Then you can change the code in your view to this:

<% if user_signed_in? && current_user.admin? %>
  # Show Admin Stuff
<% end %>

There's a few things that aren't ideal:

  1. Your attribute User.admin is a boolean, which means without adding a method in User.rb (model), you will be able to do User.admin? and it will return true or false.

  2. It's not a good idea to create your admin user in your method that checks if the current user is an admin. The quickest way is to go into rails console (via your terminal) and updating a User to admin = true, eg User.last.update_attribute(:admin, true) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM