2016-03-04 55 views
1

我有两种模式。 OfficeEmployeeEmployee具有office_id作为foreign_key。这些表是在名称空间下生成的。那么,哪个是正确的?我应该在belongs_to中使用has_many中的foreign_key子句吗?

class MyNamespace::Office < ActiveRecord::Base 
    has_many :employees, foreign_key: 'office_id' 
end 

class MyNamespace::Employee < ActiveRecord::Base 
    belongs_to :office, foreign_key: 'office_id' 
end 

或者

class MyNamespace::Office < ActiveRecord::Base 
    has_many :employees 
end 

class MyNamespace::Employee < ActiveRecord::Base 
    belongs_to :office, foreign_key: 'office_id' 
end 

我觉得第二个例子是正确的,因为对我来说,不是很有意义声明foreign_key在has_many关系。一位同事认为第一个例子是正确的。但我没有找到太多的这个问题的参考。那么,有人知道哪个是正确的例子吗?为什么?

回答

3

您可以指定前缀以正确映射到DB中的表名,并根本删除foreign_keys和MyNamespace。

class Office < ActiveRecord::Base 
    self.table_name_prefix = 'namespace_' 
    has_many :employees 
end 

class Employee < ActiveRecord::Base 
    self.table_name_prefix = 'namespace_' 
    belongs_to :office 
end 
+0

我更新了我的问题。因为我忘记提到这些表是在名称空间下生成的,所以在数据库中,该表的格式为“my_namespace_employee”和“my_namespace_office”。型号名称与表名不匹配:/ –

+0

我已更新我的答案 –

相关问题