dennismonsewicz
dennismonsewicz

Reputation: 25542

Rails 3 ActiveRecord Class Methods

In my feeble attempt to write better Model methods, I am failing hard. Which in turn, has brought me to ask my question here.

Here is my Model:

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

This is what I am trying to do with my scope

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

So, essentially see if I can tell if the group is expired. Now, I know I can write this in my controller in my activerecord where statement, but I am trying to better understand handling data in models with Rails

Upvotes: 0

Views: 382

Answers (2)

Robin
Robin

Reputation: 21884

That's not what scopes are for ;)

To do what you want, just add an instance method:

def expired?
    expiration_date > Time.now
end

An expired scope would be use to select expired groups:

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

And you would use it like that:

Group.expired
# or
user.groups.expired
#etc

Upvotes: 2

lucapette
lucapette

Reputation: 20724

As far as I can understand from your g.expired? you're looking for an instance method and for this very reason you can use scope. It serves a different purpose. So, if you really want an instance method you should do something like:

class Group < ActiveRecord::Base

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

By the way, if you want, say, all the expired groups you were on the right path with scope. But be aware of the fact you need a lambda to properly evaluation the query:

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

Upvotes: 2

Related Questions