Rails 3: owned_to, has_one and Migrations

I am new to Rails and I come to it from the background of Django. I agreed that the models and schema of the database are separate in Rails, online Django. However, I am still accessing the migration.

My question is pretty simple - how can I add a relationship to a model using migration? For example, I have Artist and Song as empty models that are subclassed by ActiveRecord::Base at the moment, without any relationship.

I need to go to this:

 class Artist < ActiveRecord::Base has_many :songs end class Song < ActiveRecord::Base belongs_to :artist end 

But how can I change the scheme to reflect this using rails g migrate ? I am using Rails 3.1.3.

+4
source share
3 answers

You need to add the foreign key to the migration file, for example:

 def change create_table :songs do |t| t.references :artist end add_index :songs, :artist_id end 
+4
source

Now, in Rails 4 you can do:

 class AddProcedureIdToUser < ActiveRecord::Migration def change add_reference :users, :procedure, index: true end end 

to existing model

+6
source

You can create a migration

 rails g migration AddProcedureIdToUser procedure:references 

thanks

+4
source

Source: https://habr.com/ru/post/1384481/


All Articles