I'm working on a photo gallery app. Photo has a belongsTo relationship to Album (Album has_many realtionship to Photo) How do I create the migration that adds this relationship to the database correctly? I have tried - rails generate add_album_to_photo but that comes th开发者_如何学JAVArough as an empty migration. I could use a push in the right direction.
Assuming tables albums and photos exist already, all you have to do is add a column album_id to your photos table:
class AddAlbumToPhoto < ActiveRecord::Migration
  def self.up
    add_column :photos, :album_id, :integer
  end
  def self.down
    remove_column :photos, :album_id
  end
end
Or:
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
Or if you insist on generating the code:
rails g migration add_album_to_photo album_id:integer
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论