【发布时间】:2017-05-25 15:29:10
【问题描述】:
我有一个 Rails 3.2 应用程序,我想为多个客户端和一个应用程序使用一个数据库。因此,对于每个模型,我都创建了一个名为account_id 的字段,现在我想添加一个全局范围来过滤日志用户的account_id 的基中的行(account_id 是一个会话参数)。所以在初始化时我创建了一个文件并把这些代码放了
module ActiveRecord
# = Active Record Named \Scopes \
module Scoping
module Default
module ClassMethods
def unscoped #:nodoc:
return (block_given? ? relation.scoping { yield } : relation).where(account_id: Thread.current['account_id'].id)
end
def default_scope(scope = {})
scope = Proc.new if block_given?
if scope.kind_of?(Array) || scope.is_a?(Hash)
scope.merge!({:conditions=>{account_id:Thread.current['account_id'].id}})
end
self.default_scopes = default_scopes + [scope]
end
end
end
end
end
如果我使用用户 account_id=2 登录一切正常,但如果在同一时刻我使用 account_id=3 登录另一个浏览器或计算机 ...我有很多错误并且在日志中,我已经看到应用程序使用account_id=2,同时使用account_id=3。
有什么解决办法吗?我如何重写default_scope(scope = {})?其他想法?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 default-scope