views:

52

answers:

1

Hi,

i don't understand this little thing:

Suppose, we have "Condition" model

class Condition < ActiveRecord::Base
end

Why Condition.all works ?

Condition.all.each { |p| do_something }

This syntax tells us, that we have "Condition" class-object instanciated somewhere ?

Or is it some convention over configuration case ?

I asking this, because i want to override Condition.all method to return Conditions, sorted by "created_at" field value ?

I don't need to use sort method in place, i want to insert Conditions to, because in the entire project i need only one sorting

Thanks

+7  A: 

Person.all is just an alias for Person.find(:all) (see the documentation here).

all, like find, is a class method on ActiveRecord::Base so doesn't require an instance in order to be called.

Update

To override a class method you need to remember the self. prefix. e.g. you can override all like this:

class Condition < ActiveRecord::Base
  def self.all(*args)
    # overridden implementation here
  end
end

If you aren't clear on instance methods vs. class methods read this blog post which is a good summary,

However, if you just want to specify a default ordering you don't need to do this. You can just use default_scope:

class Condition < ActiveRecord::Base
  default_scope :order => 'created_at'
end
mikej
I chnaged Person to Condition to better reflect, what i added in my post right now.But, regards ".all" - why we don't write "Conditions::all". Is Condition - is already instantiated class object ?
AntonAL
How can i override it ?"def all" does not works ...
AntonAL
OK, when it does't require an instance in order to be called, why we call "all" as with instance ? Why not "::all" ?
AntonAL
Condition *is* an instance. It's an instance of a Class object. But don't get too tied up with that distinction, just understand that you can have class-level methods which are separate to instance-level methods
Gareth
And yes, you *can* call Condition::all and it should work exactly the same
Gareth