Reputation: 10243
class Product < ActiveRecord::Base
attr_accessible :brand_id, :name
belongs_to :brand
end
class Brand < ActiveRecord::Base
attr_accessible :name
has_many :products
end
Controller Action:
def index
@products = Product.includes(:brand)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @products }
end
end
And View:
<% @products.each do |product| %>
<tr>
<td><%= product.brand.name %></td>
<td><%= product.name %></td>
<td><%= link_to 'Show', product %></td>
<td><%= link_to 'Edit', edit_product_path(product) %></td>
<td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
I see that two queries get run:
SELECT `products`.* FROM `products`
SELECT `brands`.* FROM `brands` WHERE `brands`.`id` IN (1, 2)
I'm wondering why ActiveRecord doesn't just run the following query?
select products.*, brands.name
from products
join brands
on brands.id = products.brand_id
I think I must be missing something-- because I'm quite certain when I do something similar using .NET's Entity Framework and use Includes, there would only be one query run.
Am I missing something?
Upvotes: 1
Views: 11
Reputation: 1269
I believe the difference between ActiveRecord and Entity Framework is that Entity Framework specifically stores the schema somewhere where as ActiveRecord needs to query the database to get the schema.
So, and I could be wrong, if ActiveRecord did a query like
select products.*, brands.*
from products
join brands
on brands.id = products.brand_id
It would not know where the product fields ended and the brands fields began.
Upvotes: 1