用户在我的rails db schema中有许多配置文件,例如admin和merchant等。现在我如何编写代码来检查当前用户是否是管理员? 更多信息:用户表是独立的,配置文件表是分开的。它们通过has_and_belongs_to_many:profiles
在用户模型中链接这是我的架构:
create_table "profiles", force: true do |t|
t.string "name", null: false
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "profiles", ["name"], name: "index_profiles_on_name", unique: true, using: :btree
create_table "profiles_roles", id: false, force: true do |t|
t.integer "profile_id"
t.integer "role_id"
end
create_table "profiles_users", id: false, force: true do |t|
t.integer "profile_id"
t.integer "user_id"
end
create_table "role_types", force: true do |t|
t.string "name"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", force: true do |t|
t.string "name", null: false
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "role_type_id"
t.string "display_name"
end
add_index "roles", ["name"], name: "index_roles_on_name", unique: true, using: :btree
create_table "users", force: true do |t|
t.string "username", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "email", default: ""
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "first_name"
t.string "last_name"
t.string "msisdn"
t.string "city"
t.string "address"
t.integer "e_bills_count", default: 0
t.string "notification_url"
t.string "notification_params", default: [], array: true
t.boolean "notification_post", default: true
t.string "legal_info"
t.string "greeting_message"
t.boolean "email_notification", default: false
t.string "website"
t.string "logo"
t.string "signature"
t.string "additional_notification_params", default: ""
t.string "currency"
end
答案 0 :(得分:1)
没有单一的教条式的“轨道式”和#39;去做这个。最简单的方法是添加一个布尔列' is_admin'。但是因为这不适合其他场景,所以这通常会扩展到一个有额外角色的架构。 table和与用户模型的has_many关系。
Thare也是更复杂的授权模型的宝石:
https://github.com/ryanb/cancan/wiki/Role-Based-Authorization
示例实现可以是:
self.profiles.map(&:name).include?('admin')