Why MyModel.all works in Rails?
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开发者_Go百科-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
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
精彩评论