2014-11-03 61 views
0

我下面就ActiveRecord的一個在線教程,其中定義了一個表和它的關係時,教練寫了下面的代碼:ActiveRecord:模型中的數據庫關係定義與表設置中的外鍵定義?

#Setup of the database table 
class CreateTimeEntries < ActiveRecord::Migration 
    def change 
    create_table :time_entries do |t| 
     t.float :time 
     t.belongs_to :customer 
     t.belongs_to :employee 
     t.timestamps 
    end 
    end 
end 

#Relationship definition in the relevant model 
class TimeEntry < ActiveRecord::Base 
    belongs_to :customer 
    belongs_to :employee 
end 

不是那些線路冗餘?

#in table setup 
t.belongs_to :customer 
t.belongs_to :employee 

#in the relevant model 
belongs_to :customer 
belongs_to :employee 

我瞭解,在db表設置的線路都在這裏定義外鍵,怎麼就那麼我們需要在模型中定義的關係呢? 我認爲外鍵自己定義了這種關係。

我在這裏錯過了什麼?在網上找不到明確的答案。非常感謝。

回答

0

這是兩個完全不同的方法:

在遷移belongs_to :parent只創建parent_id列 - 當您運行遷移時,纔會執行。這裏沒有定義外鍵 - 導軌不相信這些是必要的。這僅僅是一個語法糖:遷移的運行

t.integer :parent_id 

後,所有的軌知道的是,你的TimeEntry模型parent_id列 - 它絕對沒有別的意思。這就是爲什麼你必須給它的含義belongs_to - 在ActiveRecord對象的上下文中執行的這個方法將創建關聯 - 它將創建一個方法parent,它具有所有的後臺功能來獲取引用的對象以及提供一些驗證和保存鉤子可以更輕鬆地處理對象。這並不總是必要的。

總之,沒有belongs_to你只能夠調用my_model.parent_id(由belongs_to移民提供),但不my_model.parent

+0

晶瑩剔透。非常感謝 ! – 2014-11-03 10:25:37

0

他們有不同的目標。 migartion定義de db表並允許創建或修改表。該模型定義了Rails框架如何使用數據庫表。

你必須定義你的模型是這樣的:

class Customer < ActiveRecord::Base 
    has_many :time_entries 
end 

class Employe < ActiveRecord::Base 
    has_many :time_entries 
end 

class TimeEntry < ActiveRecord::Base 
    belongs_to :customer 
    belongs_to :employe 
end 

在遷移水平,belongs_to :customer添加一個字段customer_id了涉及型號。

相關問題