add has_many and belongs_to migration from command line

不打扰是莪最后的温柔 提交于 2019-12-25 02:23:01

问题


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

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

My models look like this:

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

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

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


回答1:


You need to create a new migration to add foreign key

rails g migration add_designer_id_to_item designer_id:integer

and run

rake db:migrate


来源:https://stackoverflow.com/questions/20041474/add-has-many-and-belongs-to-migration-from-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!