繁体   English   中英

相互引用两个模型

[英]referencing two models to each other

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

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?

TL;博士; 当你使用has_many through时,你需要额外的模型,你不需要它用于habtm关联

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM