Question

I have these three Active Record models:

class Event < ActiveRecord::Base
  has_many :event_categories, inverse_of: :event
  has_many :categories, through: :event_categories
end

class EventCategory < ActiveRecord::Base
  belongs_to :event
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :event_categories
  has_many :events, through: :event_categories
end

I think the relations are good.

If I want to know what Events have a Category, for example id=5.. I do:

Category.find(5).events

But, if I want to know all Events for more than one category, for example:

Category.where(:id => [3,5]).events

It isn't working. Any ideas?

Was it helpful?

Solution

Please note, when you do has_many :events in a model, Active Record defines a method of name events for that class.

When you do Category.find(5).events, you get events associated with one object (i.e. Category.find(5)) , however Category.where(:id => [3,5]) returns an array of Category objects, so you can't use events function on an array, Only way to get events for all search results is iterate over them and access them individually, something like following:

 all_events = Category.where(:id => [3,5]).inject([]) {|res,cat| res << cat.events}

Above code will do one query per iteration, to avoid this, we can include events, in the first query itself, like following, which will provide result in only one query:

 all_events = Category.includes(:events).where(:id => [3,5]).inject([]) {|res,cat| res << cat.events}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top