【问题标题】:HABTM association between models named with underscore用下划线命名的模型之间的 HABTM 关联
【发布时间】:2015-07-27 18:07:41
【问题描述】:

我遇到了以下问题: 我的 Rails 应用程序有很多模型,但我对其中两个之间的关联有疑问:

class RedArticle < ActiveRecord::Base
  has_and_belongs_to_many :red_sections
end

class RedSection < ActiveRecord::Base
  has_and_belongs_to_many :red_articles
end

似乎是标准设置。但是当我测试关联时,例如使用

RedArticle.first.red_sections

然后我得到以下错误:

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'clubago.red_articles_sections' 不存在:显示完整字段 red_articles_sections

所以我的 Rails 会寻找一个名为 red_articles_sections 的表,而不是 red_articles_red_sections(它存在于我的数据库中)。有人知道这个问题来自哪里吗?我尝试将数据库重命名为 red_articles_sections 并且成功了,但我认为这不是一个好的解决方案。

【问题讨论】:

    标签: ruby-on-rails activerecord associations has-and-belongs-to-many


    【解决方案1】:

    这有帮助吗

    class RedArticle < ActiveRecord::Base
     has_and_belongs_to_many :red_sections, join_table: "red_articles_red_sections"
    end
    
    
    class RedSection < ActiveRecord::Base
      has_and_belongs_to_many :red_articles, join_table: "red_articles_red_sections"
    end
    

    参考:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many(选项)

    【讨论】:

      【解决方案2】:

      这是故意的,实际上。 Rails docs解释一下:

      如果您的表格共享一个公共前缀,则它只会在开头出现一次。例如,表“catalog_categories”和“catalog_products”生成连接表名“catalog_categories_products”。

      所以,您的快速修复是正确的。但是,我个人的建议是从您的两个模型中删除 Red 前缀 - 除非您的架构中有一个名为 Article 的不同模型,Red 真的添加了什么吗?

      Athar's solution 也可以,如果您想保留旧的连接表名称。

      【讨论】:

        猜你喜欢
        • 2012-12-14
        • 2019-01-29
        • 2013-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多