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}