加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:创建自定义数据类型/创建简写

发布时间:2020-12-16 20:33:57 所属栏目:百科 来源:网络整理
导读:我想知道如何创建一个在rake迁移文件中使用的自定义数据类型.示例:如果要创建模型,可以在迁移文件中添加列.它可能看起来像这样: def self.up create_table :products do |t| t.column :name,:string t.timestamps end end 我想知道如何创建这样的东西: t.
我想知道如何创建一个在rake迁移文件中使用的自定义数据类型.示例:如果要创建模型,可以在迁移文件中添加列.它可能看起来像这样:
def self.up
    create_table :products do |t|
      t.column :name,:string
      t.timestamps
    end
  end

我想知道如何创建这样的东西:

t.column :name,:my_custom_data_type

其原因是创建一个“货币”类型,它只不过是十进制,精度为8,比例为2.由于我只使用MySQL,所以这个数据库的解决方案就足够了.

感谢您的反馈和意见!

解决方法

你想要做的是定义一个新的列创建方法,提供创建自定义类型的选项.这通过在迁移中添加一个像t.integer一样的方法来完成.诀窍在于确定哪里可以添加该代码.

您的初始化程序目录中的某些地方放置了这段代码:

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

现在你可以使用货币方法做定义一个货币列任何时候你需要它.

例:

def self.up
  create_table :products do |t|
    t.currency :cost
    t.timestamps
  end
end

要将货币列添加到现有表中:

def self.up
  change_table :products do |t|
    t.currency :sell_price
  end
end

警告:我没有时间去测试,所以没有保证.如果不行,那至少应该让你走上正轨.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读