Rails:创建自定义数据类型/创建简写 [英] Rails: creating a custom data type / creating a shorthand
问题描述
我想知道如何创建自定义数据类型以在rake迁移文件中使用。示例:如果要创建模型,则可以在迁移文件内添加列。可能看起来像这样:
I am wondering how I could create a custom data type to use within the rake migration file. Example: if you would be creating a model, inside the migration file you can add columns. It could look like this:
def self.up
create_table :products do |t|
t.column :name, :string
t.timestamps
end
end
我想知道如何创建这样的东西:
I would like to know how to create something like this:
t.column :name, :my_custom_data_type
创建例如 currency类型的原因,无非一个小数,精度为8,小数位数为2。由于我仅使用MySQL,因此该数据库的解决方案就足够了。
The reason for this to create for example a "currency" type, which is nothing more than a decimal with a precision of 8 and a scale of 2. Since I use only MySQL, the solution for this database is sufficient enough.
感谢您的反馈和意见!
推荐答案
您想要做的是定义一个新的列创建方法,该方法提供用于创建自定义类型的选项。从本质上讲,这是通过添加在迁移中行为类似于 t.integer ...
的方法来完成的。技巧是弄清楚将代码添加到何处。
What you're looking to do is define a new column creation method that provides the options to create your custom type. Which is essentially done by adding a method that behaves like t.integer ...
in migrations. The trick is figuring out where to add that code.
在初始化器目录中的某些位置应放置以下代码段:
Some where in your initializers directory place this snippet of code:
module ActiveRecord::ConnectionAdapters
class TableDefinition
def currency (*args)
options = args.extract_options!
column_names = args
options[:precision] ||= 8
options[:scale] ||= 2
column_names.each { |name| column(name, 'decimal', options) }
end
end
end
现在您可以使用货币方法在需要时随时定义货币列。
Now you can use the currency method do define a currency column any time you need it.
示例:
def self.up
create_table :products do |t|
t.currency :cost
t.timestamps
end
end
要将货币列添加到现有表中:
To add a currency column to an existing table:
def self.up
change_table :products do |t|
t.currency :sell_price
end
end
注意:我还没有时间进行测试,因此无法保证。如果它不起作用,则至少应该使您走上正确的轨道。
Caveat: I haven't time to test it, so there's no guarantees. If it doesn't work, it should at least put you on the right track.
这篇关于Rails:创建自定义数据类型/创建简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!