add has_many and belongs_to migration from command

2019-08-29 11:40发布

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条回答
走好不送
2楼-- · 2019-08-29 12:13

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
查看更多
登录 后发表回答