我需要将belongs_to更改为HABTM

时间:2016-09-27 23:49:15

标签: ruby-on-rails ruby-on-rails-4

我有一篇属于类别的文章

我有一个类别has_many文章

我需要对此进行更改,以便某个类别包含多篇文章,且文章包含多个类别。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您需要编写一个新的迁移来删除文章表中的类别ID。注意:所有类别ID的数据都将丢失

    remove_column :articles, :category_id

HABTM引用的另一次迁移。

    def change
        create_table :categories_articles do |t|
        t.references :category, index: true, foreign_key: true
        t.references :articles, index: true, foreign_key: true
      end
    end

现在有文章模型和类别模型。删除has_many关系并在类别和文章模型中添加如下HABTM。

    #in articles model
    has_and_belongs_to_many :categories
    #in categories model
    has_and_belongs_to_many :articles

最后运行

    rake db:migrate
相关问题