Rails 3.0 の scope で first は使えない

例えば次のような scope を costs.rb に定義します。

class Cost < ActiveRecord::Base
  scope :next, lambda{|day|
    where(["occured_on > ?", day]).order("occured_on").first
  }
end

これはシンタックスエラーにはなりませんが、実行すると次のようなエラーになります。

NoMethodError: undefined method `includes_values' for #

これは scope が ActiveRecord のオブジェクトを返さないといけないためで、first を使うと単体のモデルが返されてしまい、エラーになります。上のようなケースでは first を外に出してあげると問題なく動作するようです。

class Cost < ActiveRecord::Base
  scope :next, lambda{|day|
    where(["occured_on > ?", day]).order("occured_on")
  }
end

ここでコントローラ等で

next_one = Cost.next(Date.today).first

とすると内部では LIMIT 1 がかかった SQL が発行されるため、無駄にメモリを使う心配はありません。