Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: belongs_to, has_one and Migrations

I'm new to Rails, and I'm coming to it from a Django background. I've come to terms with the fact that models and the database schema are separate in Rails, online Django. However, I'm still getting to grips with migrations.

My question is fairly simple - how do I add a relationship to a model using a migration? For example, I have Artist and Song as empty models that subclass ActiveRecord::Base at the moment, with no relationships whatsoever.

I need to move to doing this:

class Artist < ActiveRecord::Base
  has_many :songs
end

class Song < ActiveRecord::Base
  belongs_to :artist
end

But how do I change the schema to reflect this using rails g migrate? I'm using Rails 3.1.3.

like image 997
Sam Starling Avatar asked Dec 03 '11 15:12

Sam Starling


3 Answers

Now, in Rails 4 you can do:

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

to an existing Model

like image 184
Dinatih Avatar answered Nov 14 '22 14:11

Dinatih


You have to add the foreign key in your migration file, something like this:

def change
  create_table :songs do |t|
    t.references :artist
  end

  add_index :songs, :artist_id
end
like image 21
rabusmar Avatar answered Nov 14 '22 15:11

rabusmar


You can generate migration

rails g migration AddProcedureIdToUser procedure:references 

Thanks

like image 6
Prasanth_Rubyist Avatar answered Nov 14 '22 14:11

Prasanth_Rubyist