我遇到以下问题: 我的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
并且它有效,但我不认为这是一个很好的解决方案。
答案 0 :(得分:0)
这会有帮助吗
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(选项)
答案 1 :(得分:0)
实际上,这是故意的。 Rails docs解释它:
如果您的表共享一个公共前缀,它只会在开头出现一次。例如,表“catalog_categories”和“catalog_products”生成连接表名称“catalog_categories_products”。
所以,你的快速修复是正确的。但是,我的个人建议是从你的两个模型中删除Red
前缀 - 除非你的模式中有一个名为Article
的不同模型,Red
是否真的添加任何内容?
Athar's solution也可以。