从命令行添加 has_many 和 Beings_to 迁移 [英] add has_many and belongs_to migration from command line

查看:33
本文介绍了从命令行添加 has_many 和 Beings_to 迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成了两个模型,现在想要实现活动记录关联.

I generated two models and now want to implement active record associations.

我有设计师和物品.一个Item属于一个Designer,一个Designer拥有多个Item.

I have Designers and Items. An Item belongs to a Designer and a Designer has many Items.

我的模型如下所示:

app/models/item.rb:

app/models/item.rb:

class Item < ActiveRecord::Base
    belongs_to :designer
    validates :designer_id, presence: true

end

app/models/designer.rb:

app/models/designer.rb:

class Designer < ActiveRecord::Base
    has_many :items, dependent: :destroy 

end

即使在我运行 rake db:migrate 之后,我的迁移也没有反映新的关系.他们展示了原始一代:

Even after I run rake db:migrate my migrations don't reflect the new relationship. They show the original generation:

class CreateDesigners < ActiveRecord::Migration
  def change
    create_table :designers do |t|
      t.string :name
      t.string :country
      t.string :about

      t.timestamps
    end
  end
end

class CreateItems < ActiveRecord::Migration
  def change
    create_table :items do |t|
      t.string :title
      t.string :price
      t.string :description

      t.timestamps
    end
  end
end

如何进行迁移,以便数据库反映我在模型中编写的 has_many 和 Beings_to 关系?

How do I make a migration so the database reflects the has_many and belongs_to relationships I wrote in my models?

推荐答案

需要新建迁移添加外键

rails g migration add_designer_id_to_item designer_id:integer

然后运行

rake db:migrate

这篇关于从命令行添加 has_many 和 Beings_to 迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆