Add Rows on Migrations

前端 未结 5 1830
故里飘歌
故里飘歌 2020-12-15 18:41

I\'d like to know which is the preferred way to add records to a database table in a Rails Migration. I\'ve read on Ola Bini\'s book (Jruby on Rails) that he does something

5条回答
  •  余生分开走
    2020-12-15 18:54

    The Rails API documentation for migrations shows a simpler way to achieve this.

    http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

    class CreateProductCategories < ActiveRecord::Migration
      def self.up
        create_table "product_categories" do |t|
          t.string name
          # etc.
        end
    
        # Now populate the category list with default data
    
        ProductCategory.create :name => 'Books', ...
        ProductCategory.create :name => 'Games', ... # Etc.
    
        # The "down" method takes care of the data because it
        # drops the whole table.
    
      end
    
      def self.down
        drop_table "product_categories"
      end
    end
    

    Tested on Rails 2.3.0, but this should work for many earlier versions too.

提交回复
热议问题