【问题标题】:HMT Naming Similarity IssueHMT 命名相似性问题
【发布时间】:2016-08-06 16:32:59
【问题描述】:

我有两个两个模型:CompanyCompanyType。我需要一个公司可以拥有并属于多种类型的关联设置。基于命名连接模型的 Rails 约定,我在 sort've 绑定。我不能命名我的加入模型CompanyType,因为它显然存在。在这种情况下你会怎么做?

class Company < ApplicationRecord
end

class CompanyType < ApplicationRecord
end

【问题讨论】:

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


    【解决方案1】:

    如果您不打算向其附加更多内容,则可以通过定义 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

    如果你需要连接模型,我猜你可以按照同一个文档中解释的方法。

    【讨论】:

    • 感谢您的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多