问题
I have two models:
class Calendar < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :calendar
end
I need to output all calendars with nested events as json and I can do it like so:
Calendar.all.to_json(:include => :events)
But I also need to filter events, for example:
where(:name => 'bla')
How would I do that? So far my solution is manually convert each calendar to hash, filter events and convert them to hash as well, then append events to calendar hash and convert to_json at the end. But I'm hoping there is a nicer approach.
回答1:
I think this should work:
Calendar.includes(:events).where('events.name' => 'bla').to_json(:include => :events)
来源:https://stackoverflow.com/questions/12633546/filter-nested-model-collections-in-to-json-in-rails