HMT命名相似性问题

时间:2016-08-06 16:33:00

标签: ruby-on-rails join associations naming-conventions has-many-through

我有两个模型:CompanyCompanyType。我需要一个公司可以拥有并属于多种类型的关联设置。基于命名连接模型的rails约定,我是一个绑定。我无法命名我的连接模型CompanyType,因为这显然存在。你在这些情况下做了什么?

class Company < ApplicationRecord
end

class CompanyType < ApplicationRecord
end

1 个答案:

答案 0 :(得分:0)

如果您不打算添加更多内容,可以通过定义has_and_belongs_to_many关联来跳过创建连接模型:

class Company < ApplicationRecord
  has_and_belongs_to_many :company_types
end

class CompanyType < ApplicationRecord
  has_and_belongs_to_many :companies
end

# No join model needed

您仍需要迁移才能创建表格。请参阅:http://apidock.com/rails/v4.2.1/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

如果您需要连接模型,我可以按照同一文档中说明的方法进行操作。