Rails 的 unscope
WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.
Article info
分類於:
⟩
⟩
標籤:
日期:
創作於:2017/04/29,最後更新於:2017/10/27。
合計:271字
Like
or Dislike
About the Author
很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯
More to explore
UnScope 用的人應該不多,我能不用也不用,但是,總有用到時,要配合它,一開時寫SQL時,最好就是能知道他的限制。
UnScope 只能用在Hash mode,不能用在 SQL 的 Where 字串內,有點可惜...
在 SQL 的 Hash,正常
在 SQL 的字串,不能動作
irb> @blogs = Blog.where("block=0").to_sql
=> "SELECT \"blogs\".* FROM \"blogs\" WHERE (block=0) ORDER BY \"blogs\".\"created_at\" DESC"
irb> @blogs = Blog.where("block=0").unscope(where: :block).to_sql
=> "SELECT \"blogs\".* FROM \"blogs\" WHERE (block=0) ORDER BY \"blogs\".\"created_at\" DESC"
在 SQL 的字串,全部 unscope 可行!
irb> @blogs = Blog.where("block=0").unscope(:where).to_sql
=> "SELECT \"blogs\".* FROM \"blogs\" ORDER BY \"blogs\".\"created_at\" DESC"
rewhere 也一樣:
irb> @blogs = Blog.where("block=0").rewhere(spam_block: 1)
SELECT "blogs".* FROM "blogs" WHERE (block=0) AND "blogs"."block" = $1 ORDER BY blogs"."created_at" DESC [["block", 1]]
解決的方法式混合兩種
irb> @blogs = Blog.where(block: 1).where("role_id <> 0").count
SELECT COUNT(*) FROM "blogs" WHERE "blogs"."block" = $1 AND (role_id <> 0) [["block", 1]]
=> 3
irb> @blogs = Blog.where(block: 1).where("role_id <> 0").unscope(where: :block).count
SELECT COUNT(*) FROM "blogs" WHERE (role_id <> 0)
=> 634
irb> @pc_blogs = PcBlog.where(spam_block: 1).where("pc_role_id <> 0").unscope(where: :spam_block).where("spam_block_editor_id is not null").count
SELECT COUNT(*) FROM "pc_blogs" WHERE (pc_role_id <> 0) AND (spam_block_editor_id is not null)
=> 25
irb> @pc_blogs = PcBlog.where(spam_block: 1).where("pc_role_id <> 0").unscope(where: :spam_block).where("spam_block <>0").count
SELECT COUNT(*) FROM "pc_blogs" WHERE (pc_role_id <> 0) AND (spam_block <>0)
=> 19