开发者

Query on two HABTM models (Rails3)

I have two models, Clients and Items with a HABTM association. I would like to find the fastest way to select all Clients, which have several (more than one) of the items (or a certain number of items).

class Client < ActiveRecord::Base
  has_and_belongs_to_many :items
end

class Item < ActiveRecord::Base
  has_and_belongs_to_many :clients
end

The开发者_如何转开发 query below fetches the clients, which have any ONE item from the list:

required_item_ids = Item.where(:kind => :book).collect(&:id)
Client.join(:items).where(:items => {:id => required_item_ids})

But needed is the list of clients having SEVERAL or ALL of the required items.

I believe this is a simple question as I am a newbie to Rails, but I looked through all similar questions here and in some other places and did not find the answer.


If this is a one-off job, then you could get this list via looping through all the clients in Ruby. Something like:

clients_with_more_than_one_book_items = []
book_items = Item.where(:kind => :book)

Client.find_each do |client|
  books_count = 0
  client.items.each do |item|
     if book_items.include?(item)
        books_count += 1
     end
  end

  clients_with_more_than_one_book_items << client if books_count > 1
end

However, that may take a while to run if you have lots of clients and items, so if this is a query that you're running often, it's probably a good idea to add a books_count attribute to the Client model, and to add code (within callbacks on the model) that keep this updated as a kind of counter cache.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜