Rails:join table name

I just came across the naming convention for a has_and_belongs_to_many relation’s join table.

If you have tables products and categories, which have a many to many relationship, a product can belong to many categories and a category can contain many products. What would you name the joining table, products_categories or categories_products.

Rails convention says use categories_products.

Rails assumes that a join table is named after the two tables it joins (with the names in alphabetical order). If you use some other name, you would need an additional declaration.

Unless there is a very compelling reason to do so, one should stick with the convention.
Reason: For maximum productivity don’t go against Rails’ philosophy “Convention over configuration”

Comments

  1. So you add one line of code. I don’t think it’s a big deal, and there doesn’t seem to be any other ripple-through effects. It’s unfortunate that they don’t mention it in the documentation that you have that option though. I don’t even remember what is… I think :join_table_name

    Just remember that when you override table names, when you use AR, it still expects you to use your model name and plural of your model name.

  2. so how does one specify a join table, where one of the tables being joined is itself a join table?

    For example, I have a table of questions, and a table of answers. I have a join table called answers_questions. The answers_questions table tells me which answers are possible to which questions. However, I kept the primary key ‘id’ column here, because it’s more efficient for me when creating user records to have a single integer reference that tells me what question and what answer they gave.

    So my join table has the id column, and now I want to create another table to join user id’s with the id’s of their question-answer pairs. What do I name this join table? First glance would seem to be “answers_questions_users”. Does rails support that?

    And if not, what is the conventional Rails declaration to use such a setup?

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

35 − thirty two =