rails migration不会更新数据库

时间:2014-03-12 21:04:04

标签: ruby-on-rails ruby database rails-activerecord rails-migrations

我想创建客户端和项目之间的关联,客户端has_many项目和项目belongs_to客户端。但是迁移并没有创造出例如" client_id"。

这是我的模特:

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

class Project < ActiveRecord::Base
    belongs_to :client
end

这是我的迁移文件:

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

我应该手动完成吗?

3 个答案:

答案 0 :(得分:3)

您还需要在迁移中指定引用。引用被添加到具有外键的表中。

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

答案 1 :(得分:1)

如果您已经运行了迁移,则只需添加新的迁移

即可

rails generate migration AddClientToProjects client:references

这将生成如下迁移:

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

并执行rake db:migrate


如果您想在CreateProjects迁移本身中添加引用。

然后执行以下操作:

如果已经运行了

,则回滚迁移

rake db:rollback VERSION=version_number

其中,

将version_number替换为迁移文件名中提到的版本号。

例如:如果您的迁移文件名为20140125190622_create_projects.rb 那么命令应该是

rake db:rollback VERSION=20140125190622

使用

销毁当前迁移

rails destroy migration CreateProjects

并使用以下方法再次创建

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

这将创建如下迁移:

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

在此之后运行rake db:migrate

答案 2 :(得分:0)

您可以在此处找到当前问题的解决方案:http://guides.rubyonrails.org/association_basics.html

您的项目迁移需要一行t.integer:client_id

或t.references:来自vee的客户也应该这样做