Skip to content

Instantly share code, notes, and snippets.

@tai2
Created September 21, 2016 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tai2/665aefa4bd3427754ceb2fad395339c7 to your computer and use it in GitHub Desktop.
Save tai2/665aefa4bd3427754ceb2fad395339c7 to your computer and use it in GitHub Desktop.
ActiveRecordで未公開の記事を含むカテゴリを抽出する
class Category < ActiveRecord:Base
has_many :posts
...
end
# publised :boolean
class Post < ActiveRecord:Base
...
end
Category
.left_outer_joins(:posts)
.group('categories.id')
.having('SUM(CASE WHEN NOT posts.published THEN 1 ELSE 0 END) > 0')
@f96q
Copy link

f96q commented Sep 21, 2016

なるほど、全記事が公開されてるカテゴリ一覧だと、各カテゴリごとの件数出して
各カテゴリごとにそれぞれ全部publishedになってるか、みないとできないので
なかなか綺麗にいかないですね。

@yatmsu
Copy link

yatmsu commented Sep 21, 2016

http://qiita.com/k0kubun/items/80c5a5494f53bb88dc58
これよくまとまってます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment