Forum: Ruby on Rails many to one relation.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
pantouffe (Guest)
on 2007-01-19 19:04
(Received via mailing list)
-i searched through the news group but couldn't find the answer for my
problem.
example:

----------- classes ----------
class Car < ActiveRecord::Base
  has_one :colour
  def after_create()
    colour = Colour.new
    colour.name = 'colour1'
    colour.save
  end
end

class Chair < ActiveRecord::Base
  has_one :colour
end

class Colour < ActiveRecord::Base
end
-------------- tables ---------
create table cars(id int PRIMARY KEY NOT NULL AUTO_INCREMENT,name
varchar(50),colour_id int NOT NULL, primary key(id));

create table chairs(id int PRIMARY KEY NOT NULL AUTO_INCREMENT,name
varchar(50),colour_id int NOT NULL);

create table colours(id int PRIMARY KEY NOT NULL AUTO_INCREMENT,name
varchar(50));

- i consider it a many to one relation because diferent types of items
are refering to one type (Car and Chair both have colour).
- i wrote the models as above i create a Car object, i save it but
alwayes my colour_id in the database remains 0.
  I would appreciate if your could give me a hint.
Bala P. (Guest)
on 2007-01-19 22:17
(Received via mailing list)
When you say "car has one colour", the other side of the relationship
must
read "colour belongs to car". Now the entity that has the belongs to
relationship is the one which will have the foreign key, in this case it
will be car_id.

So, your tables must define the foreign keys prperly and also declare
the
belongs to relationship. Make the changes and run again and see if the
record gets populated.
This topic is locked and can not be replied to.