相互引用两个模型

时间:2013-04-12 20:52:52

标签: ruby-on-rails

我正在阅读其中一本初学者书籍,并在参考文献中有这个例子:

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

所以这两个模型都是通过habtm以两种方式连接的,就像上面的代码一样。但是,这本书还告诉我,我应该提供这样的迁移:

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

我的问题:为什么?为什么我需要创建此迁移而不是模型articles_categories?

1 个答案:

答案 0 :(得分:2)

<强> TL;博士;当您使用has_many through时,您需要额外的模型,habtm关联不需要它

如果您不关心中间的表(这里是articles_categories),则会使用has_and_belongs_to_many关联。我所说的“不”真正关心的是,此表中不需要额外的数据。只是在这里告诉您哪些类别与给定文章相关,哪些文章与给定类别相关。 为此,has_and_belongs_to_many关联很好,因为您不必创建模型,它只需要连接表。

如果你在某个表格中需要一些额外的数据,比如标签,日期,状态或任何东西,那么拥有专用模型真的很方便,所以你可以明确地操纵它。 对于这些情况,您应该使用has_many :through association

如果您需要更多信息,我建议您阅读关于关联的rails指南,这是一个良好的开端。当然,如果我的解释不够明确,请告诉我,我会添加更多细节。

相关问题