Add Rows on Migrations

前端 未结 5 1818
故里飘歌
故里飘歌 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 19:06

    You should really not use

    ProductType.create
    

    in your migrations.

    I have done similar but in the long run they are not guaranteed to work.

    When you run the migration the model class you are using is the one at the time you run the migration, not the one at the time you created the migration. You will have to be sure you never change your model in such a way to stop you migration from running.

    You are much better off running SQL for example:

    [{name: 'Type', ..}, .. ].each do |type|
      execute("INSERT INTO product_types (name) VALUES ('#{type[:name]} .. )
    end
    

提交回复
热议问题