Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 我应该在has\u many中使用foreign\u key子句吗?_Ruby On Rails_Database_Ruby On Rails 4_Activerecord - Fatal编程技术网

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