0

I have got the following problem: My Rails app has many models, but I have a problem with the association between two of them:

class RedArticle < ActiveRecord::Base
  has_and_belongs_to_many :red_sections
end

class RedSection < ActiveRecord::Base
  has_and_belongs_to_many :red_articles
end

Seems to be a standard setup. But when I test the association for example with

RedArticle.first.red_sections

Then I get the following error:

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'clubago.red_articles_sections' doesn't exist: SHOW FULL FIELDS FROM red_articles_sections

So my Rails looks for a table called red_articles_sections instead of red_articles_red_sections (which exists in my database). Does somebody know where this Problem comes from? I tried to rename the database to red_articles_sections and it worked, but I don't think that this is a good solution.

4b0
  • 21,981
  • 30
  • 95
  • 142
LeMark88
  • 89
  • 1
  • 5

2 Answers2

0

will this help

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

Reference: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many (options)

Athar
  • 3,258
  • 1
  • 11
  • 16
0

This is on purpose, actually. The Rails docs explain it:

If your tables share a common prefix, it will only appear once at the beginning. For example, the tables “catalog_categories” and “catalog_products” generate a join table name of “catalog_categories_products”.

So, your quick fix was correct. However, my personal recommendation would be to drop the Red prefix from both of your models -- unless you have a different model named Article in your schema somewhere, does the Red really add anything?

Athar's solution would also work, if you want to keep the old join table name.

Community
  • 1
  • 1
Robert Nubel
  • 7,104
  • 1
  • 18
  • 30