![](/img/trans.png)
[英]Is a migration necessary for generating an ID in a has_many/belongs_to relationship?
[英]add has_many and belongs_to migration from command line
我生成了兩個模型,現在想實現活動記錄關聯。
我有設計師和物品。 一個項目屬於一個設計器,而一個設計器有多個項目。
我的模型如下所示:
app / models / item.rb:
class Item < ActiveRecord::Base
belongs_to :designer
validates :designer_id, presence: true
end
app / models / designer.rb:
class Designer < ActiveRecord::Base
has_many :items, dependent: :destroy
end
即使在我運行rake db:migrate
我的遷移也不會反映新的關系。 他們顯示了原始的一代:
class CreateDesigners < ActiveRecord::Migration
def change
create_table :designers do |t|
t.string :name
t.string :country
t.string :about
t.timestamps
end
end
end
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.string :title
t.string :price
t.string :description
t.timestamps
end
end
end
如何進行遷移,以便數據庫反映我在模型中編寫的has_many和belongs_to關系?
您需要創建一個新遷移以添加外鍵
rails g migration add_designer_id_to_item designer_id:integer
並運行
rake db:migrate
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.