【问题标题】:add has_many and belongs_to migration from command line从命令行添加 has_many 和 belongs_to 迁移
【发布时间】:2013-11-18 06:30:14
【问题描述】:

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

我有设计师和物品。一个项目属于一个设计师,一个设计师有很多项目。

我的模型如下所示:

app/models/item.rb:

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

end

app/models/designer.rb:

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

end

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

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 和 belongs_to 关系?

【问题讨论】:

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


    【解决方案1】:

    你需要创建一个新的迁移来添加外键

    rails g migration add_designer_id_to_item designer_id:integer
    

    然后运行

    rake db:migrate
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多