简体   繁体   中英

Calculate quantity based on one Category attribute in Active Admin Dashboard (Rails 3.2/ active-admin 1.0)

I am building a daily deal app to learn on Ruby on Rails.

My basic models are:

  • Deals

  • Agencies (the one who would feature the deal).

One of the attributes of Agencies is "agency_type" where I classify them by type (advertising agency, digital agency...).

A deal belongs_to a agency and Agencies has_many deals

What I'd like to do is put on my admin interface on Active Admin a very basic table giving the "top type of agencies" based on their number of deals.

Unfortunately in the table I have on active admin, I don't manage to "merge" the various entities. You can see the problem on the picture below:

在此处输入图片说明

You can see the problem the first line:

  • it's like this because there is one Agency called "Agency A" that has no deals so far but is an "Advertising Agency" type

  • the second line: another agency, "agency B" has 2 deals so far and is also of type "Advertising Agency"

What I'd like rails and active admin to do is sum those and merge them into 1 single line "advertising Agency". How can I do that?

Here is my code:

column do
    panel "Top Type of Agencies" do
      table_for Agency.order('created_at desc').limit(10) do
        column ("Agency Type"), :agency_type 
        column ("NB of deals") do |agency_type|
          agency_type.deals.count 
        end
      end
    end    
  end

There are two ways to do this. In pure ruby:

# (this is a bad idea)

Or utilizing SQL:

data = Agency.joins('left outer join deals on deals.agency_id = agencies.id').
  select('agencies.agency_type, count(deals.id) as deals_count').group 'agency_type'

panel "Top Agency Types" do
  table_for data do
    column :agency_type
    column '# of Deals', :deals_count
  end
end

Disclaimer: Not tested

In order to iterate through agency types in active admin you should have a different model with agency types.

#agency.rb
has_one :agency_type
def count_deals_by_agency_type(agency_type)
   where(:agency_type_id => agency_type).deals.count
end

In active admin

column do
    panel "Top Type of Agencies" do
      table_for AgencyType.all do |agency_type|
        column ("Agency Type"), agency_type.name
        column ("NB of deals"), Agency.count_deals_by_agency_type(agency_type.id) 
      end
    end    
 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM