LoginSignup
8
3

More than 5 years have passed since last update.

rails default_scopeの使い所

Last updated at Posted at 2016-07-21

Railsのdefault_scopeは悪だ!(default_scope is evil) ということらしい
http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html

rails default_scopeは悪と言われることがあって、自分もはまったことあるのでほぼ使わないようにしてた.
railsドキュメントのサンプルはあまりよくない例だと思う.
でも、元のテーブルに属性を指定するのではなく、以下のように参照専用/既存のデータを表すために使えばわかりやすいし、強力だと思う.

class PublishedArticle < Article
  default_scope -> { where(status: :published) }
  has_many :comments
end
class Last7Days < Article
  default_scope ->{
    where( created_at: 7.days.ago..Time.zone.now )
  }

  def days_remain_till_get_older
    return 0 if created_at < 7.days.ago
    ((created_at - 7.days.ago) / (60*60*24)).ceil
  end
end

ふつうのscope使ってできるケースもあるが、このようにクラスに切り出せたほうが有効な場面も多い.
STIにも似てるけど、typeカラムのようなものは不要なので自由度高く条件を設定できる.
CQRSの考えとも親和性が高いと思う.

modelがreadonlyであることを保証したい場合は以下が参考

http://stackoverflow.com/questions/5641410/is-there-an-easy-way-to-make-a-rails-activerecord-model-read-only
http://d.hatena.ne.jp/akishin999/20130718/1374100143

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3