定义一个自定义的“可链接”ActiveRelation方法,如`order`和`limit`

时间:2011-01-06 05:25:14

标签: ruby-on-rails activerecord

Rails有这些可爱的chainable方法。我该如何添加自己的?我想在模型中定义一个类方法,我想从中调用我的自定义方法,但这只能在“链”的开头工作:

class << self
  def order_by_specialness
    order(:specialness)
  end
end

我怀疑我需要以某种方式扩展ActiveRecord::Relation,因为这是每个可链接查询方法返回的内容。但是从那里开始,我不知所措。

1 个答案:

答案 0 :(得分:3)

您想使用scope

scope :order_by_specialness, order(:specialness)

致电:

User.order_by_specialness.first

虽然使用order_by_specialness并不能真正为您节省时间。你应该使用像special

这样的东西
User.special.first