Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

ruby on rails - add associations to exisiting models

I'm wondering how I can add associations to my models. Suppose, I generate two models

rails generate model User
rails generate model Car

Now I want to add an associations so that the models acquire the form

class User < ActiveRecord::Base
  has_many :cars
end
class Car < ActiveRecord::Base
  belongs_to :user
end

The question is: how to apply this modification by migrations in order to obtain cars_users table in the database? I'm planning to use that table in my code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

belongs_to association expect an association_id column in its corresponding table. Since cars belongs_to user, the cars table should have a user_id column. This can be accomplished 2 ways.

first, you can generate the column when you create the model

rails g model car user_id:references

or just add the user_id after you create the model like Richard Brown's answer. Be careful that if you use integer instead of references, you'd have to create the index yourself.

rails g migration add_user_id_to_cars user_id:integer

then in the generated migration, add

add_index :cars, :user_id

UPDATE:

As Joseph has mentioned in the comments, the need to add the index manually has already been addressed in the current version of Rails. I think it was introduced in Rails 4. You can read more of it in the official Rails guide for migrations. The gist of it is running the following generator

bin/rails g migration add_user_to_cars user:references

will create a migration with a line similar to

add_reference :cars, :user, index: true

This will add a user_id column to the cars table and it will also mark that column to be indexed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...