Question

I want to create association between client and project, client has_many projects and project belongs_to client. But migration doesn't create for example "client_id".

It is my models :

class Client < ActiveRecord::Base
    has_many :projects, dependent: :destroy
end

class Project < ActiveRecord::Base
    belongs_to :client
end

It is my migration files:

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string :name
      t.datetime :start_date
      t.datetime :end_date
      t.boolean :active

      t.timestamps
    end
  end
end

class CreateClients < ActiveRecord::Migration
  def change
    create_table :clients do |t|
      t.string :name

      t.timestamps
    end
  end
end

Should I do it manually?

Was it helpful?

Solution

You need to specify the reference in migration as well. The reference is added to the table which has the foreign key.

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string :name
      t.datetime :start_date
      t.datetime :end_date
      t.boolean :active

      t.references :client # Add this line

      t.timestamps
    end
  end
end

OTHER TIPS

If you have already run the migration then, you could just add a new migration as

rails generate migration AddClientToProjects client:references

This will generate a migration as below:

class AddClientToProjects < ActiveRecord::Migration
  def change
    add_reference :projects, :client, index: true
  end
end

and do rake db:migrate.


If you want to add the reference in the CreateProjects migration itself.

Then do the following:

Rollback the migration,if its already run

rake db:rollback VERSION=version_number

where,

Replace version_number with the version number mentioned in the migration filename.

For eg: If your migration filename is 20140125190622_create_projects.rb then command should be

rake db:rollback VERSION=20140125190622

Destroy the current migration using

rails destroy migration CreateProjects

and create it again using:

rails generate migration CreateProjects name start_date:datetime end_date:datetime active:boolean client:references

This will create a migration as follows:

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string :name
      t.datetime :start_date
      t.datetime :end_date
      t.boolean :active

      t.references :client, index:true # You could also add it manually to existing migration

      t.timestamps
    end
  end
end

Run rake db:migrate after this.

You can find the solution to your current problem here: http://guides.rubyonrails.org/association_basics.html

your project migration needs a line t.integer :client_id

or t.references :client from vee should also do the trick

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top