sparkle
sparkle

Reputation: 7390

Get all data from all tables (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")

This query retrieve only the "programs" table (I think because the "group by" clause). How I could retrieve all data from all tables (programs, programs_schedules, channel) ?

class Program < ActiveRecord::Base

belongs_to :channel
has_many :program_schedules

Ruby on Rails 3.2

Postgresql 9.2

Upvotes: 0

Views: 670

Answers (1)

user1003545
user1003545

Reputation: 2118

Are you looking for the eager loading of associations provided by the includes method ?

Eager loading is a way to find objects of a certain class and a number of named associations. This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each need to display their author triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 2.


Update:
You can get the SQL as a string by appending .to_sql to your query. .explain can also help.

If you want to get the data as a hash and no more as model instances, you can serialize the result of the query and include the associations using .serializable_hash :

data.serializable_hash(include: [:program_schedules, :channel])

You can define which fields to include using :except or :only options in the same way as described here for .as_json (which acts similarly) : http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json

Upvotes: 1

Related Questions