Wednesday, 15 April 2015

ruby on rails - Topics have_many posts. Get all topics without any posts -



ruby on rails - Topics have_many posts. Get all topics without any posts -

a blog has "topics", "topics" have "posts".

how can count of topics without posts? unused topics.

topics = topic.all topics.???

topic.includes(:posts).where('posts.topic_id null').references(:posts).count

after seeing other answers, ran both statements in console.

this reply generates next query

(0.9ms) select count(distinct "topics"."id") "topics" left outer bring together "posts" on "posts"."topic_id" = "topics"."id" (posts.topic_id null)

while other reply generates 2 queries (as obvious).

(0.6ms) select "posts"."topic_id" "posts" (0.5ms) select count(*) "topics" ("topics"."id" not in (2,3,11,23))

ruby-on-rails ruby-on-rails-4 rails-activerecord

No comments:

Post a Comment