[英]rails migration doesn't update database
我想在客户端和项目之间创建关联,客户端has_many项目和项目属地对客户端。 但是迁移不会创建例如“ 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
我应该手动做吗?
您还需要在迁移中指定参考。 该引用将添加到具有外键的表中。
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
如果您已经运行了迁移,则可以添加新的迁移为
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
。
您可以在这里找到当前问题的解决方案: http : //guides.rubyonrails.org/association_basics.html
您的项目迁移需要一行t.integer:client_id
或t.references:vee的客户也应该做到这一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.