rails类或实例方法中的范围是?

时间:2012-12-31 08:56:38

标签: ruby-on-rails-3 separation-of-concerns scopes

这是一个试图了解问题和范围的铁路菜鸟的问题。

我一直认为范围是轨道中的类方法,但有一天我看到this code from DHH

module Visible
  extend ActiveSupport::Concern`

  module ClassMethods
    def visible_to(person)
      where \
        "(#{table_name}.bucket_id IN (?) AND
          #{table_name}.bucket_type = 'Project') OR
         (#{table_name}.bucket_id IN (?) AND
          #{table_name}.bucket_type = 'Calendar')",
        person.projects.pluck('projects.id'), 
        calendar_scope.pluck('calendars.id')
    end
  end
end

所以使用visible方法的方式如下:

current_account.posts.visible_to(current_user)

这令我感到困惑。 Self这里是一组帖子,所以我们在实例上进行操作,而可见方法似乎是用作类方法。是不是david试图将类方法称为动态范围?请有人澄清一下吗?

1 个答案:

答案 0 :(得分:3)

继承ActiveRecord :: Base的类的类方法也可以用作范围(在ActiveRecord Relation对象上)。

由于模块Visible旨在混合到继承ActiveRecord :: Base的模型中,因此其类方法visible_to也可以用作范围。

如果这不能解决问题,您可以通过以下方式实现一个范围,该范围可以吸引所有成年用户(年龄> 20岁):

class User < ActiveRecord::Base
  scope :adult, lambda { where("age > ?", 20) } # with a scope

  class << self
    def adult # with class method
      where("age > ?", 20)
    end
  end
end

User.adult

完全相同