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?
There's a few things that aren't ideal:
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.
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, e.g. User.last.update_attribute(:admin, true)
.
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 %>