I’m new to rails and ruby, and after trying to get this to work
correctly for hours, I thought I’d give this forum an try.
I’ve setup a trivial project just to mess around with Rails database
naming conventions and associations.
I’ve got a table called Pets, and a table called Types.
Pets contains a list of pets, Parky the cat, Daisy the dog, etc, And
Types contains a list of different pet types, dog - cat - fish - bird -
etc.
Pets table
CREATE TABLE pets
(
id
int(11) NOT NULL auto_increment,
name
varchar(20) default NULL,
pet_id
int(11) default NULL,
PRIMARY KEY (id
)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
Types table
CREATE TABLE types
(
id
int(11) NOT NULL auto_increment,
pettype
varchar(11) default NULL,
PRIMARY KEY (id
)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
What I want to do is to associate the pet_id from Pets with the id from
types, and can do that in SQL like this:
select pets.*, types.pettype
from pets, types
where pets.id = 1
and pets.pet_id = types.id
In Rails, I have two models, 1 for pets, 1 for types
class Type < ActiveRecord::Base
belongs_to :pet
end
class Pet < ActiveRecord::Base
has_one :type, :foreign_key => “id”
end
What I end up with is this SQL statement out of Rails:
select pets.*, types.pettype
from pets, types
where pets.id = 1
and pets.pet_id = 1
Where 1 is the primary key (id) of the pets row.
Just wondering what I’m doing wrong.
Thanks!