1
votes

I need to be able to display the count for an associated model with specific conditions. I have a Mall model that has_many Shops, a Shop model which belongs_to Mall and has_many Sales, and a Sale model that belongs_to Shop.

Basically what I want to do is to first Iterate through each mall to display the :name of each mall, and then I would like to show how many total Sale records exist for shops belonging to each mall. However, I only want to show the number of Sale records with the following criteria: Sale.where('offer_end >= ?', Date.today).

Im not really sure how to achieve this due to Sales not having a direct connection to Malls. The following code is my best attempt to achieve this but its not working.

<% @malls.each do |mall| %>
  <%= mall.name %> - <%= mall.shops.sales.where('offer_end >= ?', Date.today).count %>
<% end %>       

Mall Model

class Mall < ActiveRecord::Base
    has_many :mall_shops
    has_many :shops, :through => :mall_shops
    validates :name, presence: true, uniqueness: true
end

Shop Model

 class Shop < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, :through => :categorizations
    has_many :mall_shops
    has_many :malls, :through => :mall_shops
    has_many :sales, dependent: :destroy
end

Sale Model

class Sale < ActiveRecord::Base
    belongs_to :shop
end
1

1 Answers

3
votes

First, you can nest has_many :through associations:

In Mall.rb:

has_many :sales, through: :shops

You can also create a scope for active sales:

In Sale.rb:

scope :active, -> do
   where('offer_end >= ?', Date.today)   # Pay attention to time zone here
end

Now, you can get active sales for a mall:

@mall = Mall.find(...)
@mall.sales.active.count