Leo
Leo

Reputation: 2103

referencing two models to each other

i'm going through one of ror beginners books, and it has this example on references:

class Article < ActiveRecord::Base
  attr_accessible :body, :excerpt, :location, :published_at, :publisher, :title

  validates :title, :presence => true
  validates :body, :presence => true

  belongs_to :user
  has_and_belongs_to_many :categories
end

class Category < ActiveRecord::Base
  attr_accessible :name

  has_and_belongs_to_many :articles
end

so these two models are meant to be connected by habtm in both ways, just like in the code above. but, the book also tells me i should provide such a migration:

class CreateArticlesCategories < ActiveRecord::Migration
  def up
        create_table :articles_categories, :id => false do |t|
        t.integer :article
        t.integer :category
    end
  end

  def down
    drop_table :articles_categories
  end
end

My question: why? why do i need to create this migration and not a model articles_categories?

Upvotes: 0

Views: 47

Answers (1)

pjam
pjam

Reputation: 6356

tl;dr; You need the extra model when you're using a has_many through, you don't need it for the habtm association

The has_and_belongs_to_many association is meant to be used when you don't really care about the table in the middle (here it's articles_categories). What I mean by "don't" really care is that, there are no extra data needed in this table. It's only here to tell you which categories are related to a given article, and which articles are related to a given category. For that purpose the has_and_belongs_to_many association is great cause you don't have to create the model, it only needs the join table.

If somehow you need some extra data in that table, like tags, dates, status, or anything, then it would be really handy to have a dedicated model, so you could explicitly manipulate it. For those cases, you should use the has_many :through association

If you need more information, I suggest you read the rails guide about association, it's a good start. And of course if my explanation is not clear enough, please tell me, and I'll add more details.

Upvotes: 2

Related Questions