从所有表中获取所有数据(Postgresql)

时间:2013-01-10 23:21:01

标签: ruby-on-rails-3 postgresql activerecord rails-postgresql

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

1 个答案:

答案 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

相关问题