开发者

Rails find all with association

开发者 https://www.devze.com 2022-12-29 11:35 出处:网络
I have what I think is a very simple problem (famous last words)... 开发者_JS百科I have a Category model that has_and_belongs_to_many Events. I want to construct a simple and efficient query that fin

I have what I think is a very simple problem (famous last words)...

开发者_JS百科

I have a Category model that has_and_belongs_to_many Events. I want to construct a simple and efficient query that finds all categories that have 1 or more events. (using Rails 3)

I'm sure I'm having a dumb moment here - any help appreciated :)


How about:

Category.find :all,
  :conditions => 'id in (select distinct category_id from categories_events)'

You could also add this as a named scope to your Category class so that you can say Category.with_events e.g.

class Category < ActiveRecord::Base
  named_scope :with_events, 
    :conditions => 'id in (select distinct category_id from categories_events)'
end
0

精彩评论

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