【发布时间】: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:migrate,rails 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