I have two models Horse and Race.
class Horse < ActiveRecord::Base
has_many :races
end
class Race < ActiveRecord::Base
belongs_to :horse
end
Now I want to use the new rails 3 query interface to see the Horse name and all its races.
Horse.joins(:races) # I get an active record relation that only displays horse data
Horse.joins(:races).count #Yields 31 the exact number of races.
Horse.joins(:races).all #Yields an Array of 31 Horse, but no race data
Horse.joins(:races).all.select("horses.*, starters.*") #Yields active record relation with only Horse data.
Question 1: What’s the correct query to yield complete horse and race records.
Question 2: What’s the correct query to yield the horse name and all of the race record.
I know this is very basic, but I’m stumped. I sense I’d doing something wrong with the relation.
From what I can see I don’t thing you’re doing anything wrong with your relations.
If you want to see all horses with each of their races:
Assuming I understand your question, your use of
joins(:races)is irrelevant here. First, it will not automatically pull any data from the races table. It will simply add an inner join between horses and races. If horse N has 10 races, that query will then return 10 instances of horses N, which is probably not useful in this instance.The
includes(:races)above isn’t strictly necessary – it just loads all the races at once with one query, as opposed to n queries (n being the number of horses). Just saves time and resources.