Search code examples
ruby-on-railsruby-on-rails-3many-to-manymodel-associationshas-and-belongs-to-many

Rails 3 HABTM one-liner


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

Solution

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