【问题标题】:Migrations From Custom Generator Don't Migrate来自自定义生成器的迁移不迁移
【发布时间】:2014-11-14 05:31:52
【问题描述】:

我正在创建一个宝石

我有一个生成器,可以根据您选择的名称创建迁移

rails g my_generator MODEL

我没有使用rails'

rails g migration XYZ

但实际上是在复制模式的样子...例如:如果用户键入以下内容

rails g my_generator Item

你得到:

class CreateItem < ActiveRecord::Migration
  def change
    create_table "items", force: true do |t|
      t.string   "title"
      t.integer  "color_id"
      t.integer  "size_id"
      t.datetime "created_at"
      t.datetime "updated_at"
      t.integer  "base_product_id"
      t.integer  "stock_qty"
    end
  end
end

迁移的名称是 (my_generator)create_items.rb 我没有在迁移开始时插入时间戳。这确实是rails g model Item 的迁移与我从生成器中获得的迁移之间的唯一区别。

我的迁移没有做任何事情,但我测试了创建一个新模型,并运行 rake db:migraterails g model 迁移,我的没有。

这是我的生成器:

 class Rails::ShiftedCommerceGenerator < Rails::Generators::NamedBase
      def create_main_model
        create_file "app/models/shifted_commerce/#{plural_name.singularize}.rb", <<-FILE
          class #{class_name} < ActiveRecord::Base
            belongs_to :base_#{plural_name.singularize}
            has_many :line_items
            belongs_to :size
            belongs_to :color
            validates_uniqueness_of :base_#{plural_name.singularize}_id, :scope => [:size_id]

            def is_base_#{plural_name.singularize}?
                return true if self.class.name == "Base#{class_name}"   
            end
            def is_#{plural_name.singularize}?
                return true if self.class.name == "#{class_name}"   
            end
            def in_stock
              self.stock_qty > 0
            end

          end
        FILE
      end
      def create_main_migration
        create_file "db/migrate/shifted_commerce_create_#{plural_name}.rb", <<-FILE
        class Create#{class_name} < ActiveRecord::Migration
            def change
                create_table :#{plural_name}, force: true do |t|
                  t.string   :title
                  t.integer  :color_id
                  t.integer  :size_id
                  t.datetime :created_at
                  t.datetime :updated_at
                  t.integer  :base_product_id
                  t.integer  :stock_qty
                  t.timestamps

                end
            end
        end
        FILE
      end
    end

【问题讨论】:

  • 我会发布我的生成器...

标签: ruby-on-rails ruby ruby-on-rails-4 migration


【解决方案1】:

确保在生成自己的迁移时包含时间戳

(不使用 rails g 迁移)

您的生成器应该包含以下内容:

create_file "db/migrate/#{Time.now.strftime("%Y%m%d%H%M%S")}_create_#{plural_name}.rb", <<-FILE

.strftime 方法是一种将时间戳放入迁移文件的方法,就像 rails 对其进行格式化一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2022-06-29
    • 2019-06-17
    • 2016-06-29
    • 2012-06-26
    • 2018-12-27
    • 1970-01-01
    相关资源
    最近更新 更多