Ruby on rails 我应该在has\u many中使用foreign\u key子句吗?
我有两个模型<代码>办公室和员工<代码>员工将Ruby on rails 我应该在has\u many中使用foreign\u key子句吗?,ruby-on-rails,database,ruby-on-rails-4,activerecord,Ruby On Rails,Database,Ruby On Rails 4,Activerecord,我有两个模型办公室和员工员工将办公室id作为外键。这些表是在命名空间下生成的。那么,哪一个是正确的 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
办公室id
作为外键。这些表是在命名空间下生成的。那么,哪一个是正确的
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
或
class MyNamespace::Office
我认为第二个例子是正确的,因为对我来说,在
关系中声明外键没有意义。一位同事认为第一个例子是正确的。但是我没有找到太多关于这个主题的参考文献。那么,有人知道哪个是正确的例子吗?为什么 您可以指定前缀,以便正确映射到DB中的表名,并完全删除外键和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
班级办公室
我更新了我的问题。因为我忘了提到表是在名称空间下生成的,所以在数据库中,表是my\u namespace\u employee
和my\u namespace\u office
。模型名称与表名称不匹配:/
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