0

在我编写更好的模型方法的微弱尝试中,我失败了。这反过来又让我在这里问我的问题。

这是我的模型:

class Group < ActiveRecord::Base
  # Because of inheritance issues with ActiveRecord
  # We tell this Relation to use a "false" column to persuade
  # The relation to push forward without worrying about Inheritance
  self.inheritance_column = :_type_disabled

  scope :expired?, where('expiration_date > ?', Time.now)
end

这就是我试图用我的scope

g = Group.find(91)
g.expired?

所以,基本上看看我是否可以判断该组是否已过期。现在,我知道我可以在我的控制器中的 activerecord where 语句中写这个,但我试图更好地理解处理模型中的数据Rails

4

2 回答 2

2

据我所知,您g.expired?正在寻找实例方法,因此您可以使用scope。它有不同的用途。所以,如果你真的想要一个实例方法,你应该这样做:

class Group < ActiveRecord::Base

  def expired?
    self.expiration_date > Time.now
  end
end

顺便说一句,如果你想要所有过期的组,那么你就在正确的路径上。但请注意,您需要一个 lambda 来正确评估查询:

scope :expired, lambda { where('expiration_date > ?', Time.now) }
于 2012-04-23T21:10:01.403 回答
2

那不是作用域的用途;)

要做你想做的,只需添加一个实例方法:

def expired?
    expiration_date > Time.now
end

范围将expired用于选择过期组:

scope :expired, lambda { where('expiration_date > ?', Time.now) }

你会这样使用它:

Group.expired
# or
user.groups.expired
#etc
于 2012-04-23T21:10:47.377 回答