0

I need a one-liner to generate a has_and_belongs_to_many join table or else I will go back to Django for its simpler many-to-many constructs.

rails 3 generate model article_tags [..]

Models

# article.rb
has_many :articles_tags
has_many :tags, :through => :articles_tags

# tag.rb
has_many :articles_tags
has_many :articles, :through => :articles_tags

# article_tag.rb
belongs_to :tag
belongs_to :article
Johannes Pille
  • 4,073
  • 4
  • 26
  • 27

4 Answers4

3

Ohh wait haha, I think this might do the trick:

rails g model articles_tags article:references tag:references --no-id --no-timestamps

I wonder if there is anyway to suppress the model file's creation (article_tags.rb) so that I can just use the standard has_and_belongs_to_many syntax without having to specify a :through param? I'm looking for the ultimate one-liner: Tip of the hat to anyone who can improve the above one-liner to enable only the use of has_and_belongs_to_many syntax without a join model! Else, I'm going back to Django, with it's built-in ManyToManyFields.

Cole Diamond
  • 1,301
  • 10
  • 9
2

It sounds like you're looking for the standard has_and_belongs_to_many:

# article.rb
has_and_belongs_to_many :tags

# tag.rb
has_and_belongs_to_many :articles

Your join table would be called articles_tags, and need just contain two columns, article_id and tag_id (no id column needed since it isn't a model).

This is in the Rails Guide to Associations. I highly recommend becoming familiar with the Rails Guides.

It's almost too simple for a generator. All you need are two empty model classes and the join table, which would be defined in a migration like so:

def self.up
  create_table :articles_tags, :id => false do |t|
    t.integer :article_id
    t.integer :tag_id
  end
end

def self.down
  drop_table :articles_tags
end
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
1

Don't know if this is still of interest after so much time, but I think you can take a look at https://github.com/zealot128/ruby-habtm-generator: it's a Rails generator that generates the correct migration for the HABTM table.

0

Using generate will create two indexes

Check this answer https://stackoverflow.com/a/9825571/643500

Community
  • 1
  • 1
Sully
  • 14,672
  • 5
  • 54
  • 79