开发者

Defining a custom "chainable" ActiveRelation method like `order` and `limit`

开发者 https://www.devze.com 2023-02-02 12:39 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消