[英]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.