2010-07-11 78 views
0

這裏是客戶:如何添加一列以引用RoR上的另一個表?

class CreateCustomer < ActiveRecord::Migration 

     def self.up 
     create_table :customers do |t| 
      t.column :email,  :string, :null => false 

     end 
     end 

     def self.down 
     drop_table :customers 
     end 
    end 

這是客戶信息:

class CustomerInfo < ActiveRecord::Migration 

    def self.up 
    create_table :statuses do |t| 
     t.column :statuses,  :string, :null => false 

    end 
    end 

    def self.down 
    drop_table :status 
    end 
end 

我想要做的是客戶和客戶信息有一一對應的關係。我如何在新遷移中完成此操作?謝謝。

回答

0

當您想在Rails中使用1對1時,您必須決定哪個模型將存儲外鍵。在你的情況下,你可能需要狀態來存儲fk,所以在狀態表中添加一個名爲customer_id的整數列。然後,您可以在Customer和Status上添加has_one/belongs_tobelongs_to總是與外鍵一起進入模型。

而且我不知道,如果Rails會喜歡你和奇異對罵你的表,那麼你可能會做一些額外的工作,如果你真的想調用它,而不是「狀態」

「狀態」
+0

因此,我不需要在我的遷移中添加額外的代碼?只要去模型,並設置has_one和belongs_to關係,所有的魔法將起作用? – Tattat 2010-07-11 07:40:47

+0

你需要在遷移中添加外鍵(customer_id),但在此之後,是的,只是has_one/belongs_to是它 – x1a4 2010-07-11 07:46:12

0

你可以嘗試在你的下一個遷移之後的事情

add_column:CUSTOMER_INFOS,:CUSTOMER_ID,:整數:引用=> 「客戶」:空=>:真

然後你就可以添加HAS_ONE/belongs_to在Customer和Cusomer_infos上。

您還可以執行SQL語句。

聲明= 「ALTER TABLE用戶更改ID號SMALLINT(5)UNSIGNED NOT NULL AUTO_INCREMENT」 的ActiveRecord :: Base.connection.execute(聲明)

您可以手動條目遷移

注意這只是一個例子。最終的SQL語句語法取決於數據庫。

相關問題