rhfannnn
rhfannnn

Reputation: 195

Ruby On Rails: Confused on ActiveRecord has_one association

Here is a simple example illustrating my problem:

Say I have two models Car and Color, where Color has two attributes Name and HexValue.

I want Car to have one color but I don't want a 1-1 relationship between Car and Color.

How can I create an association that specifies this? I know that I can add a foreign key to Car that refers to a single entry in Color but I feel like this isn't an elegant way of doing this since you will have to join the two tables to get the color of the car. Is there anyway I can create a relationship where I can just do car1.color.name to get the name of the color?

Keep in mind that I don't want to create a 1-1 relationship and I only want a set amount of colors.

Upvotes: 0

Views: 136

Answers (1)

bevanb
bevanb

Reputation: 8511

Car should belong_to :color, and color should has_many :cars.

Upvotes: 1

Related Questions