基礎
Rails 中的 scope 讓我們可以輕鬆的簡化 query 的長度,將常用的 query 設定為 scope method。
方法如下:
class Article < ActiveRecord::Base
def self.this_week
where('updated_at >= ?', 7.days.ago)
end
end
在 ActiveRecord 下面定義self.this_week,之後我們只要下Article.this_week就可以輕鬆拿到所有本週的文章。
還有另一種等值的設定方式scope :this_week, -> { 'updated_at >= ?', 7.days.ago }也可以得到相同的效果。
傳入變數
Scope 也接受傳入參數:
class Article < ActiveRecord::Base
def self.created_before(time)
where("created_at < ?", time)
end
end
Default Scope
也可以加上預設的 query :
class Client < ActiveRecord::Base
def self.default_scope
# Should return an ActiveRecord::Relation.
end
end
Merging
所有的 scope 和一般的 query 一樣可以串接著使用,並在實際的 query string 中會以AND連接。
解除 Scope
要解除 scope 只要用Article.unscoped就可以完全移除。
要注意的是在 unscoped 的後面接任何的 scope 一樣是會被移除的。