Filter nested model collections in to_json in rails

南笙酒味 提交于 2020-01-02 07:21:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!