0

default_scope的大多数模型都有current_user.company. 我在我的注册页面上使用了 client_side_validations gem,这意味着没有租户集。

当唯一性验证器在@user.emaildefault_scope 上运行时,会阻止验证正常运行(因为company_id它是 nil),因此看起来总是一个唯一的结果。

我的用户模型:

# user.rb
...
default_scope { where(company_id: Company.current_id) }
...

此查询在验证电子邮件时运行:

Started GET "/validators/uniqueness?case_sensitive=true& \
user%5Bemail%5D=me%2B40%40example.com&_=1423897339854" \
for 76.175.168.2 at 2015-02-14 07:02:30 +0000                        
  User Exists (0.4ms)  SELECT 1 AS one FROM "users" WHERE \
  "users"."company_id" IS NULL AND "users"."email" = 'me@example.com' LIMIT 1

当我default_scope从我的用户模型中删除时,我得到了正确的结果和正确的验证:

Started GET "/validators/uniqueness?case_sensitive=true& \
user%5Bemail%5D=me%2B40%40example.com&_=1423897339854" \
for 76.175.168.2 at 2015-02-14 07:02:30 +0000
  User Exists (0.4ms)  SELECT 1 AS one FROM "users" WHERE \
  "users"."email" = 'me@example.com' LIMIT 1

default_scope当这个 gem 运行电子邮件验证器时,我最实用的方法是什么?

4

3 回答 3

1

通常我会说:不要使用 default_scope 因为你会遇到各种各样的问题。在我看来,默认范围可以订购。

但在这里你可以像这样解决它:

class User < ActiveRecord::Base
 def self.default_scope
    #i don't know what company represents here
    where(company_id: Company.current_id) if Company.present?
 end
end

您可以像上面看到的那样将默认范围定义为类方法。

请参阅文档:http ://apidock.com/rails/ActiveRecord/Base/default_scope/class

于 2015-02-14T08:23:39.957 回答
0

I ended up money patching the gem within my app to fix my issue. I'll also submit the change to the gem author since I'm not sure if this is a bug or their original desired behaviour.

# lib/client_side_validations/active_record/middleware.rb

def self.is_unique?(klass, attribute, value, params)
  ...
  !klass.where(relation).exists?
end

# patched the above line to: !klass.unscoped.where(relation).exists?
于 2015-02-17T06:05:08.870 回答
0

我不认为覆盖 default_scope 是一个好主意。

您应该将逻辑移至控制器。不知道你用的是不是权威。它将提供范围功能。

如果没有,请尝试将此范围移动到控制器。

def current_users
   @users||= User.where(company_id: Company.current_id)
end
于 2015-02-14T08:16:18.273 回答