我可以使用ActiveRecord范围作为实例方法吗?

JD *_*ton 13 activerecord named-scope ruby-on-rails

我有一个作为过滤器的范围.例如:

class User
  scope :in_good_standing, -> { where(:some_val => 'foo', :some_other_val => 'bar' }
end
Run Code Online (Sandbox Code Playgroud)

因为in_good_standing依赖于多个条件,我想在以下实例上User定义:

def in_good_standing?
  some_val == 'foo' && some_other_val == 'bar'
end
Run Code Online (Sandbox Code Playgroud)

但是,我真的想避免重复实例方法和命名范围之间的逻辑.有没有办法以#in_good_standing?简单引用范围的方式定义?

编辑

我意识到这些是非常不同的概念(一个是类方法,一个是实例方法),因此我的问题.正如@MrDanA在评论中提到的,我能得到的最接近的是检查我好奇的记录是否存在于更大的范围内,这可能是我正在寻找的答案.

关于从我的示例中分离出不同范围的响应是有用的,但我正在寻找一种适用于应用程序的通用模式,其中一些非常复杂的逻辑由作用域驱动.

Pav*_*van 11

Scopes什么都不是class methods.你可以像这样定义它

def self.in_good_standing?
  #your logic goes here
end
Run Code Online (Sandbox Code Playgroud)

  • 但你仍然不能在这样的实例上调用类方法:`user = User.find(3); user.in_good_standing?`,所以这个答案没什么用. (2认同)

MrD*_*anA 10

添加原始评论作为答案:

正如@meagar所说,你不能,因为他们做的事情非常不同.您可以做的最多就是让实例方法调用范围并检查它是否是返回结果的一部分.但是,如果尚未保存实例,则无效.所以在你的方法中你可以这样做:

User.in_good_standing.where(:id => self.id).present? 
Run Code Online (Sandbox Code Playgroud)