简体   繁体   中英

Rails condition where association has_many has count more than one

Package.rb

has_many :deals

Deal.rb

belongs_to package

Now simple question is I want to get all packages where deals count is more than one. What is the best method to do it? where(:available_for_purchase => true) and self.deals.count > 0

(package.rb)

  class << self
    def available
      where(:available_for_purchase => true)
    end
  end
def self.available
  joins(:deals).where(:available_for_purchase => true).uniq
end

Joining the deals association will remove Packages without any deals ... SQL is doing the hard work here.

Then use :

Package.available

I'd use a counter-cache to give you the deal count as a column on the Package model, which will then let you use SQL for conditions.

Package.rb

has_many :deals
def with_deals
  where("deals_count > 0")
end

Deal.rb

belongs_to :package, :counter_cache => true

Then you can just call:

Package.with_deals

You can see an example of how to setup counter cache here: http://railscasts.com/episodes/23-counter-cache-column

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