Add Rows on Migrations

前端 未结 5 1829
故里飘歌
故里飘歌 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:49

    You could use fixtures for that. It means having a yaml file somewhere with the data you want to insert.

    Here is a changeset I committed for this in one of my app:

    db/migrate/004_load_profiles.rb

    require 'active_record/fixtures'
    
    class LoadProfiles < ActiveRecord::Migration
      def self.up
        down()
    
        directory = File.join(File.dirname(__FILE__), "init_data")
        Fixtures.create_fixtures(directory, "profiles")
      end
    
      def self.down
        Profile.delete_all
      end
    end
    

    db/migrate/init_data/profiles.yaml

    admin:
     name: Admin
      value: 1
    normal:
     name: Normal user
      value: 2
    

提交回复
热议问题