[英]how to add admin with devise in ROR
I am using devise gem and i wanna to create admin 我正在使用devise gem,我想创建管理员
rails g migration add_admin_to_user Rails G迁移add_admin_to_user
in the db 在数据库中
def change
add_column :users, :admin , :boolean , {default: false}
end
def user def用户
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? def用户有问题吗,如何解决?
Because you already have a boolean :admin attribute on your User model, there's a default admin?
因为您的用户模型上已经有一个布尔:admin属性,所以有一个默认的
admin?
method out of the box. 开箱即用的方法。 If you call something like
User.find(1).admin?
如果调用类似
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. 它会根据您在数据库中的值返回true或false-因此您可能不想覆盖此值。
Define a new method in your User model to assign the admin attribute. 在用户模型中定义一个新方法来分配admin属性。
def make_admin!
self.update_attribute(:admin, true)
end
Now you can call User.find(1).make_admin!
现在您可以调用
User.find(1).make_admin!
in your controller, or in rails console, or wherever you have a User instance. 在您的控制器中,在Rails控制台中,或者在您有User实例的任何地方。
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: 有一些不理想的事情:
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?
您的属性
User.admin
是一个布尔值,这意味着您无需在User.rb(模型)中添加方法,就可以执行User.admin?
and it will return true or false. 它将返回true或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, eg
User.last.update_attribute(:admin, true)
. 最快的方法是进入Rails控制台(通过您的终端)并将User更新为admin = true,例如
User.last.update_attribute(:admin, true)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.