model-scope

859 ワード

scope scopeの役割は、よく使うORM文法や複雑なORM文法を怠け者のバッグに組み合わせることです.このように、次回使うときは怠け者のバッグを出せばいいのです.例:class Topic < ActiveRecord::Base scope :recent, -> { order("created_at DESC") } end上記のcodeではrecentというscopeを定義していますが、後でrecentという命令を下すだけで下order(「created_at DESC」)と同じです.これにより、プログラムコードをより簡潔にすることができます.
使用シナリオ複雑すぎる資料照会がある場合は再利用する資料照会がある場合
使用方法パラメータなし方法class Post < ActiveRecord::Base scope :published, -> { where(published: true) }endパラメータ付き方法class Post < ActiveRecord::Base scope :created_before, ->(time) { where("created_at < ?", time) } end連続的に接続できますが、順序はclass Event < ActiveRecord::Base scope :published, -> { where(published: true) } scope :created_before, ->(time) { where("created_at < ?", time) } endに影響しません.
Event.published.created_before(Time.now)