x無法存取,你可能沒有權限或未登入。
Ff7afae5b23125e25e18ad8c0404bd78

在Rails中暫時取消default_scope來搜尋資料

2012-03-15 22:17:42 +0800hechianRuby on Rails 節點 中發起
最後由 ricky2012-03-27 15:19:01 +0800回應 , 303次閱讀

# category.rb
has_many :articles

# article.rb
belongs_to :category

default_scope where(deleted: false).order("id DESC")
def most_popular_articles
  articles.unscoped.where(deleted: false).order("visitor_counter DESC")
end

unscoped不只可以直接用在Article上,也可以搭配關連使用;加上unscoped可以在該次查詢中取消defaut_scope的設定

截至 2012-03-27 15:19:01 +0800,共收到 3 條回應
2b0e03ef8ff7fd827f57f53c79346bc3
chitsung 1樓, 於2012-03-16 12:21:02 +0800回應

不過似乎用在 STI 的子類時會無效。

Ff7afae5b23125e25e18ad8c0404bd78
hechian 2樓, 於2012-03-16 18:19:52 +0800回應

那這個時候可能就真的要自己寫SQL了吧Orz

9f31805fefe8ab45d9822d3b449f22f4
ricky 3樓, 於2012-03-27 15:19:01 +0800回應

2

需要 登入 後方可回應,如果你還沒有帳號按這裡 註冊