4

As you will see, I'm pretty new to Rails.

I am trying to follow section 3.3.2 in the RailsGuides on Active Record Associations and it says there that when defining a many to many relationship, besides adding the has_and_belongs_to_many directive to the model, you "need to explicitly create the joining table".

It then gives an example of the content of the migration file:

class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
  def change
    create_table :assemblies_parts, id: false do |t|
      t.integer :assembly_id
      t.integer :part_id
    end
  end
end

My question is: what name should I give to that file? I see that the files generated by the rails g ... command are all in the ..db\migrate folder and have a kind of timestamp at the beginning of the file. Can I use any name? I'm afraid to test and mess up the whole thing. I'm used to MS-SQL and being able to see the tables, add/modify columns, etc.

Side question: there are a few files already there, from previous migrations. How does rails know which ones were already run? And what about running them afterwards when deploying to, say, Heroku?

2 Answers 2

3

You can give any name to your migrations. Preferably something self explanatory like create_table_something. You can generate a migration by doing

rails generate migration create_assemblies_parts_joins_table

This will generate a file like below in db/migrate folder

<timestamp>_create_assemblies_parts_joins_table

Rails keeps track of already run migrations in scheme_migrations table. It stores the timestamp of all the migrations that are already run

UPDATE:

You can change the table name to whatever you want in the migration file. Table will be created with the name you give in the following line

create_table :assemblies_parts, id: false do |t|

assemblies_parts will be the table name.

Sign up to request clarification or add additional context in comments.

2 Comments

I see. And then you add the rest in the file. Sorry, I didn't understand that from the RailsGuides.
It creates a table with the name listings_locations_joins_tables. I don't want table to be pluralized. Can I change the name in the migration file?
1

You should not build the file from scratch yourself. As @Vimsha has already said - you can run a rails migration to create a join table migration for you.

The rails standard naming for a join table is to take the two names of the models you are joining, and write them in alphabetical order and pluralised.

eg if your models are "user" and "post", it would be "posts_users", but if it were "post" and "comment" it would be "comments_posts"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.