本文介绍了在Rails的to_json中过滤嵌套的模型集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:

class Calendar < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :calendar
end

我需要将所有带有嵌套事件的日历输出为json,我可以这样做:

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')

我该怎么做?到目前为止,我的解决方案是将每个日历手动转换为哈希,过滤事件并将其也转换为哈希,然后将事件追加到日历哈希并最后转换为to_json.但我希望有更好的方法.

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.

推荐答案

我认为这应该有效:

Calendar.includes(:events).where('events.name' => 'bla').to_json(:include => :events)

这篇关于在Rails的to_json中过滤嵌套的模型集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:19