我正在尝试为只有管理员才能看到的一组用户创建一个编辑页面。我创建了 3 个模型:
组.rb:
class Group < ApplicationRecord
...
has_many :user_groups, dependent: :destroy
has_many :users, through: :user_groups
...
end
用户.rb:
class User < ApplicationRecord
...
has_many :user_groups, dependent: :destroy
has_many :groups, through: :user_groups
...
end
用户组.rb:
class UserGroup < ApplicationRecord
belongs_to :user
belongs_to :group
validates_presence_of :user_id
validates_presence_of :group_id
end
用户组模型是一种包含布尔字段的模型,当用户是管理员时为“真”。这里是上述模型的 schema.rb:
create_table "groups", force: :cascade do |t|
t.string "name"
t.text "description"
t.bigint "user_id"
t.integer "type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.index ["slug"], name: "index_groups_on_slug", unique: true
t.index ["type"], name: "index_groups_on_type"
t.index ["user_id"], name: "index_groups_on_user_id"
end
create_table "user_groups", force: :cascade do |t|
t.bigint "user_id"
t.bigint "group_id"
t.boolean "is_admin"
t.boolean "is_owner"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["group_id"], name: "index_user_groups_on_group_id"
t.index ["user_id"], name: "index_user_groups_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "username", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
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", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
end
我的问题是:
如何使用 usergroups.rb 中的“is_admin”字段限定管理员的范围?我一直在尝试诸如“group.usergroups.is_admin?”之类的东西。但没有结果。
为了消除疑虑,授权将由“专家”完成,我不清楚的是如何确定管理员的范围。我正在使用 rails 5.2 和 ruby 2.6。
有什么建议吗?谢谢!
我会用这样的东西:
class GroupPolicy
def update?
UserGroup.where(user_id: user.id, group_id: group.id, is_admin: true).exists?
end
end
可以在控制器的更新方法中使用,例如
authorize @group
或在视图中 - 例如,显示编辑链接 - 像这样
<% if policy(@group).update? %>
<%= link_to "Edit group", edit_group_path(@group) %>
<% end %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句