Ruby on rails 如何定制设计以在会话中存储用户角色信息?
目前,我们对用户和角色使用两个单独的表 我使用权威进行授权,并设计进行身份验证 在很多地方,我都在做Ruby on rails 如何定制设计以在会话中存储用户角色信息?,ruby-on-rails,devise,ruby-on-rails-5,pundit,Ruby On Rails,Devise,Ruby On Rails 5,Pundit,目前,我们对用户和角色使用两个单独的表 我使用权威进行授权,并设计进行身份验证 在很多地方,我都在做current\u user.roles来获取用户的角色。主要在权威政策文件中 我想在用户登录时将用户角色存储在会话中。这样我就不会每次查询db来获取角色 任何快速的解决方案都将不胜感激。由于Pundit没有任何选项,只能传递会话或其他参数,除了当前用户和检查实体,您可以使用Rails.cache: # app/models/user.rb class User < ActiveRecord
current\u user.roles
来获取用户的角色。主要在权威政策文件中
我想在用户登录时将用户角色存储在会话中。这样我就不会每次查询db来获取角色
任何快速的解决方案都将不胜感激。由于Pundit没有任何选项,只能传递
会话
或其他参数,除了当前用户
和检查实体
,您可以使用Rails.cache
:
# app/models/user.rb
class User < ActiveRecord::Base
# ...
def cached_roles
Rails.cache.fetch "user.#{self.id}.roles" do
roles.pluck(:name)
end
end
def clear_cached_roles
Rails.cache.delete "user.#{self.id}.roles"
end
end
# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
# ...
def admin?
user.cached_roles.include? 'admin'
end
def reader?
user.cached_roles.include? 'reader'
end
end
#app/models/user.rb
类用户
要使designe缓存当前角色,您需要覆盖designe的会话控制器
# app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
def create
super
current_user.cached_roles
end
def destroy
current_user.clear_cached_roles
super
end
end
#app/controllers/users/sessions_controller.rb
类用户::会话控制器<设计::会话控制器
def创建
超级的
当前\u user.cached\u角色
结束
def销毁
当前\u用户。清除\u缓存的\u角色
超级的
结束
结束
我创建了这个,您可以使用它:在分支或拉取请求中查看我的带有Rails.cache
的解决方案变体
有关更多详细信息,请参见这些文件:
app/controllers/users/sessions\u controller.rb
spec/controllers/posts\u controller\u spec.rb
app/policies/post_policy.rb
app/models/user.rb
README.md
当前用户
和检查实体
之外,要传递会话
或其他参数,您可以使用Rails.cache
:
# app/models/user.rb
class User < ActiveRecord::Base
# ...
def cached_roles
Rails.cache.fetch "user.#{self.id}.roles" do
roles.pluck(:name)
end
end
def clear_cached_roles
Rails.cache.delete "user.#{self.id}.roles"
end
end
# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
# ...
def admin?
user.cached_roles.include? 'admin'
end
def reader?
user.cached_roles.include? 'reader'
end
end
#app/models/user.rb
类用户
要使designe缓存当前角色,您需要覆盖designe的会话控制器
# app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
def create
super
current_user.cached_roles
end
def destroy
current_user.clear_cached_roles
super
end
end
#app/controllers/users/sessions_controller.rb
类用户::会话控制器<设计::会话控制器
def创建
超级的
当前\u user.cached\u角色
结束
def销毁
当前\u用户。清除\u缓存的\u角色
超级的
结束
结束
我创建了这个,您可以使用它:在分支或拉取请求中查看我的带有Rails.cache
的解决方案变体
有关更多详细信息,请参见这些文件:
app/controllers/users/sessions\u controller.rb
spec/controllers/posts\u controller\u spec.rb
app/policies/post_policy.rb
app/models/user.rb
README.md