user1946705
user1946705

Reputation: 2888

Rails 3 - multiple associations

I have first table called Cars that contains the informations about color of the car, weight, price etc.

Then I have the second table, for example Other_informations. This table contains another informations about that car from the first table.

In the first table (Cars) is the name of the car. If I need to create an associations between these two tables, I can use:

car.rb

has many :other_informations

otherinformation.rb

belongs_to :car

In this case I have to set the name of one column in the table Other_informations on car_id and the associations will be created. To this point is everything ok.

But now - I need just one association to add (from the table Other_informations to the table Cars - the same type of associations as the first).

I tried to do something like this: car.rb

has many :other_informations

otherinformation.rb

belongs_to :car
belongs_to :car2

And then in the view used:

data.car2.name_of_the_car_from_first_table**

But this unfortunately didn't work me... can anyone help me, please, if is something like this possible to do?

Thank you in advance

Upvotes: 0

Views: 166

Answers (1)

socjopata
socjopata

Reputation: 5095

I am not sure if I understand your question - do you want to have OtherInformation to be shared among different Cars? Like OtherInformation can belong to many different Cars?

You need some kind of many-to-many relationship then. Have a read: http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

EDIT (after reading your comments):

belongs_to car, :class_name => "Car", :foreign_key => "to_col1"
belongs_to another_car, :class_name => "Car", :foreign_key => "to_col2"

That assumes that your OtherInformation has two columns in the database table: to_col1 and to_col2 And here is how associations should work:

other_info = OtherInformation.first
first_car = other_info.car
second_car = other_info.another_car
second_car_name = other_info.another_car.name
#etc...

Upvotes: 1

Related Questions