Search code examples
ruby-on-railsactiverecordassociationshas-and-belongs-to-many

HABTM association between models named with underscore


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.


Solution

  • 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)