Shun Yamada
Shun Yamada

Reputation: 979

Rails: How to count model with 0

I want to get data which has 0 votes. However when using this code, that shows only items which has more than 1 votes. Let me know how to get result which includes items has 0 votes.

def show
    @item = @article.items.joins(:votes).group('items.id').order('COUNT(items.id) DESC')
end

Upvotes: 0

Views: 68

Answers (1)

Vishal
Vishal

Reputation: 7361

You need to do a LEFT OUTER JOIN instead of an INNER JOIN,

In rails 5 and greater than 5 version

def show
    @item = @article.items.left_outer_joins(:votes).group('items.id').order('COUNT(items.id) DESC')
end

In rails 4

def show
    @item = @article.items.joins("LEFT OUTER JOIN votes ON items.id = votes.item_id").group('items.id').order('COUNT(items.id) DESC')
end

Upvotes: 2

Related Questions