范围内的实例方法

时间:2011-06-01 09:01:37

标签: ruby-on-rails-3 scope

我不知道它可能吗?我需要在范围内使用实例方法。像这样:

scope :public, lambda{ where ({:public => true}) }

并在每条记录上调用实例方法(完成?)以查看它是否已完成。这里的公共范围应该返回所有公开的记录并完成记录,记录的完成由实例方法“完成”确定?

有可能吗?

由于

2 个答案:

答案 0 :(得分:11)

范围是关于使用ARel生成查询逻辑。如果你不能代表完整的逻辑?在SQL中的方法然后你有点卡住

范围 - 至少在rails 3中 - 用于将查询逻辑链接在一起而不返回结果集。如果您需要一个结果集来完成测试,那么您需要执行类似

的操作
class MyModel < ActiveRecord::Base
  scope :public, lambda{ where ({:public => true}) }

  def self.completed_public_records
    MyModel.public.all.select { |r| r.completed? }
  end
end

# elsewhere
MyModel.completed_public_records

或者如果您需要更多灵活性

class MyModel < ActiveRecord::Base
  scope :public, lambda{ where ({:public => true}) }
  # some other scopes etc


  def self.completed_filter(finder_obj)
    unless finder_obj.is_a?(ActiveRecord::Relation)
      raise ArgumentError, "An ActiveRecord::Relation object is required"
    end
    finder_obj.all.select { |r| r.completed? }
  end
end

# elsewhere
MyModel.completed_filter(MyModel.public.another_scope.some_other_scope)

答案 1 :(得分:0)

几个月前,当我遇到同样的问题时,我为这个确切的问题创建了一个rubygem。

它允许您添加对查询结果集起作用的方法,但是将方法抽象到另一个类中,因此它不会混淆您的模型。

检查出来:https://github.com/coryodaniel/collectively