Hello all and thank you for reading this message.
I am new to RoR, and ruby too, but i am quite excited about it. I am developing a RoR project and with active record associations in the following
manner
# Tables (all tables have only one record) CREATE TABLE `webcars_development`.`cars` ( `id` int(11) NOT NULL auto_increment, `model_id` int(11) NOT NULL default '0', `photo` blob, `created_at` datetime default NULL, `updated_at` datetime default NULL, PRIMARY KEY (`id`), KEY `FK_CARS_MODELS` (`model_id`), CONSTRAINT `FK_CARS_MODELS` FOREIGN KEY (`model_id`) REFERENCES `models` (`id`) );
CREATE TABLE `webcars_development`.`models` ( `id` int(11) NOT NULL auto_increment, `name` varchar(64) NOT NULL default '', `brand_id` int(11) NOT NULL default '0', `created_at` datetime default NULL, `updated_at` datetime default NULL, PRIMARY KEY (`id`), UNIQUE KEY `name_idx` (`nome`), KEY `FK_MODELS_BRAND` (`brand_id`), CONSTRAINT `FK_MODELS_BRAND` FOREIGN KEY (`brand_id`) REFERENCES `brands` (`id`) );
CREATE TABLE `webcars_development`.`brands` ( `id` int(11) NOT NULL auto_increment, `name` varchar(16) NOT NULL default '', `created_at` datetime default NULL, `updated_at` datetime default NULL, PRIMARY KEY (`id`), UNIQUE KEY `name_idx` (`name`) );
# Models class Car < ActiveRecord::Base belongs_to :model has_one :brand, :through => :models
validates_presence_of :model_id end
class Model < ActiveRecord::Base belongs_to :brand has_one :car, :through => :models
validates_associated :brand validates_presence_of :brand, :message => 'is unknown' end
class Marca < ActiveRecord::Base has_one :model, :through => :brands end
# Controller (only index action needed for the example) class CarsController < ApplicationController def index @cars = Cars.find(:all) end end
# The view <table> <tr> <th>Brand</th> <th>Model</th> <th>Photo</th> </tr> <% for car in @cars %> <tr> <td><%=h car.model.brand.name %></td> <td><%=h car.model.name %></td> <td><%=h car.photo %></td> </tr> <% end %>
Ok, so my question is this. When i went trough the MySQL logs i saw that active record calls each table on its time instead of joining them. It runs the following queries:
SELECT * FROM `cars` SHOW FIELDS FROM `cars` SHOW FIELDS FROM `models` SELECT * FROM `models` WHERE (`models`.`id` = 1) SHOW FIELDS FROM `brands` SELECT * FROM `brands` WHERE (`brands`.`id` = 1)
should it not be running a query similar to this one?
SHOW FIELDS FROM `cars` SHOW FIELDS FROM `models` SHOW FIELDS FROM `brands` SELECT