Rails Concerns,Scopes,Devise,User.current和current_user [英] Rails Concerns, Scopes, Devise, User.current and current_user
本文介绍了Rails Concerns,Scopes,Devise,User.current和current_user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用基于状态显示记录的问题。如果您登录,您可以看到未经批准的记录,公众只能查看已批准的记录。
I'm using a concern for showing records based on status. If you are logged in you can see unapproved records and the public can only view approved records.
module Approved
extend ActiveSupport::Concern
included do
if User.current && !User.current.nil?
scope :approved, -> { where("#{self.table_name}.status_id IN (1,2,3)") }
else
scope :approved, -> { where("#{self.table_name}.status_id IN (1)") }
end
end
end
我正在使用线程来设置当前用户。
I'm using Thread to set current user.
def self.current=(user)
Thread.current[:current_user] = user
end
def self.current
Thread.current[:current_user]
end
在application_controller中我有一个before_action调用set_current_user。
And in the application_controller i have a before_action calling set_current_user.
def set_current_user
User.current = current_user
end
当我注销未批准的记录仍然从查询中拉出。似乎忽略了这个问题。
When I log out the unapproved records still pull from the query. It seems to skip over the concern.
推荐答案
包含
lambdas,但是每次都要点火。
lambdas, however, fire each time.
尝试这个:
included do
scope :approved, -> {
ids = User.current.present? ? "(1,2,3)" : "(1)"
where("#{self.table_name}.status_id IN #{ids}")
}
end
这篇关于Rails Concerns,Scopes,Devise,User.current和current_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文