2

Whenever I've had to do a HABTM in rails I've always found myself wondering if it's possible to generate the required migration from the command line.

I was hoping to save time by just doing something like this:

rails g migration tracks_podcasts tracks:references podcasts:references id:false

The above code doesn't work, and neither do several variations of it (with and without the id:false instruction)

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189
  • 1
    possible duplicate of [Do I need to manually create a migration for a HABTM join table?](http://stackoverflow.com/questions/564306/do-i-need-to-manually-create-a-migration-for-a-habtm-join-table) – Ryan Bigg Mar 12 '11 at 00:35
  • Seems to be a better answer here: http://stackoverflow.com/questions/6561330/rails-3-has-and-belongs-to-many-migration – Arcolye Nov 28 '11 at 02:53

2 Answers2

5

https://github.com/zealot128/ruby-habtm-generator is a nice option for this now.

Example:

rails g habtm user post
Todd
  • 195
  • 2
  • 11
  • Please note naming convention as of rails 4 - not implemented in ruby-habtm-generator yet: 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”. http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many – Fred Willmore Sep 10 '15 at 21:41
-2

According to the rails documentation, that should work, but you would want to replace 'references' with 'integer'. 'references' isn't a valid data type. And get rid of the id:false entry. The references and :id => false should be specified within the migration after generation. You will basically generate a basic migration with all the fields you want, then open the migration and modify it to meet your specs.

Usage:
  rails generate migration NAME [field:type field:type] [options]

Options:
  -o, --orm=NAME  # Orm to be invoked
                  # Default: active_record

Runtime options:
  -f, [--force]    # Overwrite files that already exist
  -p, [--pretend]  # Run but do not make any changes
  -q, [--quiet]    # Supress status output
  -s, [--skip]     # Skip files that already exist

Description:
    Create rails files for migration generator.
Josh Kovach
  • 7,679
  • 3
  • 45
  • 62
  • 4
    references is a valid value to use, t.references :foo translates into t.integer :foo_id. In fact you can create your own types as is seen with the devise model migrations and t.timestamps – Cluster Sep 30 '11 at 07:14
  • I support Cluster's comment. 'references' is the way to go if you wanna express a foreign key relation. http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration – gmazlami Feb 12 '16 at 10:23