1

我正在开发一个照片库应用程序。Photo 与 Album 有 belongsTo 关系(Album has_many realtionship to Photo) 如何创建迁移以正确将此关系添加到数据库?我已经尝试过 - rails generate add_album_to_photo 但这只是一个空迁移。我可以向正确的方向推动。

4

1 回答 1

3

假设表albums并且photos已经存在,您所要做的就是在表中添加一album_idphotos

class AddAlbumToPhoto < ActiveRecord::Migration
  def self.up
    add_column :photos, :album_id, :integer
  end

  def self.down
    remove_column :photos, :album_id
  end
end

或者:

class AddAlbumToPhoto < ActiveRecord::Migration
  def self.up
    change_table :photos do |t|
      t.references :album
    end
  end

  def self.down
    change_table :photos do |t|
      t.remove :album_id
    end
  end
end

或者,如果您坚持生成代码:

rails g migration add_album_to_photo album_id:integer
于 2011-08-24T01:37:02.227 回答