Rails find everything with an association

I have what I consider to be a very simple problem (famous last words) ...

I have a Category model that has_and_belongs_to_many Events . I want to create a simple and effective query that will find all categories with 1 or more events. (using Rails 3)

I am sure that I have a silent moment here - any help is appreciated :)

+4
source share
1 answer

What about:

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

You can also add this as a named scope to your Category class so you can tell Category.with_events for example.

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

Source: https://habr.com/ru/post/1308875/


All Articles