2014-11-03 60 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了涉及型号。

相关问题