命名范围扩展 - 在Do Block之外的调用方法

时间:2011-04-12 02:08:25

标签: ruby-on-rails dry named-scope

我的用户模型中有以下named_scope:

  named_scope :all_stars, :joins => [:all_stars] do
    def overall
      self.find(:all, :conditions => ['recordable_type = ?', 'User'])
    end
  end

我想这样做:

  named_scope :all_stars, :joins => [:all_stars] do
    def overall
      overall_all_stars_condition
    end
  end

  def overall_all_stars_condition
    self.find(:all, :conditions => ['recordable_type = ?', 'User']) 
  end

可以吗?

1 个答案:

答案 0 :(得分:2)

如果你可以将另一个东西放到另一个命名范围内,那么你可以将两个范围链接在一起,这样可以得到你想要的东西。

named_scope :all_stars, :joins => [:all_stars]
named_scope :overall, :conditions => ['recordable_type = ?', 'User']

然后你应该可以这样称呼它:

object.all_stars.overall.all
object.overall.all_stars.find(:all)
# etc

并创建一个执行相同操作的方法:

def overall_all_stars_condition
  self.all_stars.overall.all
end