models/host.rb
class Host < ActiveRecord::Base
has_many :report, :dependent => :delete_all
end
models/report.rb
class Report < ActiveRecord::Base
belongs_to :host
end
Now I want to select all Hosts with their reports, including Hosts that haven’t got any report.
I tried to achieve this by
list=Host.all(:joins => "left join `reports` on reports.host_id=host.id")
but it seems like Rails only selects fields from the hosts Table. So I am not able to access the report object with list[0].report.
In addition i would be much more happy doing the select without using raw SQL commands – in a more ruby-like manner.
How to get both, the host and the report in just one select and without using SQL?
You can do
Which will join the reports table and instantiated all the report objects. You can the use the loaded hosts and reports exactly as if they were being loaded on demand