Defining a custom "chainable" ActiveRelation method like `order` and `limit`
Rails has these lovely chainable methods. How do I add开发者_如何学JAVA my own? I thought of defining a class method in the model from which I want to invoke my custom method, but this would only work at the beginning of a "chain":
class << self
def order_by_specialness
order(:specialness)
end
end
I suspect I would need to extend ActiveRecord::Relation
somehow, as this is what's returned by the each of the chainable query methods. But from there, I'm at a loss.
You want to use scope
:
scope :order_by_specialness, order(:specialness)
Call with:
User.order_by_specialness.first
Although using order_by_specialness
doesn't really save you any time. You should use something just like special
:
User.special.first
精彩评论