ok so i have this helper
def playlist_count(user, site_id)
user.companies.local(site_id).map(&:playlists).flatten.count
end
which will return the playlist count for all the companies
class Playlist < ActiveRecord::Base
belongs_to :company
scope :active, where('end_date >= ? AND player_id IS NOT NULL', Date.today)
class Company < ActiveRecord::Base
has_many :playlists, :dependent => :destroy
scope :local, lambda{ |site_id| where(:site_id => site_id) }
the problem is it the helper is getting ugly and the other problem is that i need the active playlists (defined by my scope in the playlist model)
Is there a way to clean up my helper or use a scope instead to get the active playlist count for all the users companies
您可以反过来运行查询:
Playlist.active.where(:company_id => user.companies.local(site_id)).count
You can apply scopes to associations. Try this:
user.companies.local(site_id).map { |company| company.playlists.active.count }.sum
Another advantage is that it'll execute select count(*) ...
SQL statement instead of fetching all active playlists from the DB and counting them in Ruby.
If you care about performance it'll be more efficient to join tables and count active playlists for all user's companies in a single SQL statement rather than iterating over companies and making count query for each one of them.
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.