Rails: creating a custom data type / creating a shorthand

霸气de小男生 提交于 2019-12-02 20:34:13

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.

Example:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!