data = Program.joins(:program_schedules, :channel).
where(
"program_schedules.start" => options[:time_range],
"programs.ptype" => "movie",
"channels.country" => options[:country]).
where("programs.official_rating >= ?", options[:min_rating]).
group("programs.id").
order("programs.popularity DESC")
此查询仅检索“程序”表(我认为是因为“group by”子句)。 如何从所有表(程序,program_schedules,channel)中检索所有数据?
课程计划< ActiveRecord :: Base
belongs_to:频道
has_many:program_schedules
Ruby on Rails 3.2
Postgresql 9.2
答案 0 :(得分:1)
您是否正在寻找includes
方法提供的eager loading of associations?
预先加载是一种查找某个类的对象和一些命名关联的方法。这是防止可怕的1 + N问题的最简单方法之一,其中获取每个需要显示其作者的100个帖子触发101个数据库查询。通过使用预先加载,101个查询可以减少到2个。
<强>更新强>
您可以通过将.to_sql
附加到查询中来将SQL作为字符串获取。 .explain
也可以提供帮助。
如果您希望将数据作为哈希值而不再作为模型实例获取,则可以序列化查询结果并使用.serializable_hash
包含关联:
data.serializable_hash(include: [:program_schedules, :channel])
您可以使用:except
或:only
选项定义要包含的字段,方法与此处.as_json
(其行为类似)所述相同:
http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json