用下划线命名的模型之间的HABTM关联

问题描述 投票:0回答:2

我有以下问题:我的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:表'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
2个回答
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(选项)


0
投票

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

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

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

如果你想保留旧的连接表名,Athar's solution也会工作。

© www.soinside.com 2019 - 2024. All rights reserved.