Alexander
Alexander

Reputation: 127

Getting a count value between many different models and associations

I've been wondering what is the easiest way of getting a count value between several different models and associations.

I want to have something like this in my view

shop.receipts.articles.complaints.complaint_reviews.count

Here are my models and associations between them:

class Shop < ActiveRecord::Base

has_many :receipts

end

class Receipt < ActiveRecord::Base

has_many :articles, dependent: :destroy
belongs_to :shop

accepts_nested_attributes_for :articles, allow_destroy:true, :reject_if => :all_blank

end

class Article < ActiveRecord::Base

belongs_to :receipt

has_one :complaint

end

class Complaint < ActiveRecord::Base

belongs_to :article
has_many :complaint_reviews

end

class ComplaintReview < ActiveRecord::Base

belongs_to :complaint

end 

Upvotes: 0

Views: 34

Answers (2)

Alexander
Alexander

Reputation: 127

Ok so thanks to the code above I managed to come up with a working solution:

#shops_controller.rb:

def show

@count = ComplaintReview.
    joins(complaint: {article: {receipt: :shop}}).
    where(shops: {id: @shop.id}).
    count


respond_with(@shop)
end

#shops/show.html.erb:
<%= @count %>

Thanks a lot for the help.

Upvotes: 0

SHS
SHS

Reputation: 7744

I'm inferring that you want the count of all complaint_reviews that are associated with a particular shop.

In that case, the following is what you need:

shop = # get shop according to your criteria

ComplaintReview.
joins(complaint: {article: {receipt: :shop}}).
where(shops: {id: shop.id}).
count

I suppose you could save the shop joins, by applying the condition on the shop_id column of receipts; like so:

ComplaintReview.
joins(complaint: {article: :receipt}).
where(receipts: {shop_id: shop.id}).
count

Result should be the same for both if all receipts have a shop associated. But I'd opt for the first method.

The thing to keep in mind here is to 'start' with the model of which you ultimately want the count of.

Also, had there been any one-to-many relationships, you would have grouped the results by "complain_reviews.id" and then performed the count.

Upvotes: 1

Related Questions