问题
是否有内置的api、第三方gem或通用的范例,用于在rails应用程序中向数据库和从数据库中转换数据?
注意:我不寻找助手、视图模型或标准的activerecord挂钩。我需要能够在通常的钩子下面悄悄地改变数据,这样这个机制对应用程序的其余部分是分离/隐藏/未知的。
换句话说,我希望在activerecord中插入一个填充程序,它位于普通钩子的下面,并且位于数据库适配器的上面,以每个属性为基础,这将允许我透明地修改数据,就像数据库适配器的序列化程序一样。
平凡的例子

$ rails new test-app
$ cd test-app
$ bundle install
$ bundle exec rails g scaffold vehicle make model year:integer color
$ bundle exec rake db:migrate

before中,类似于:
class Vehicle < ActiveRecord::Base
  magic_shim :color, in: :color_upcase, out: :color_downcase

  private
    # Returns a modified value for storage but does not change the
    # attribute value in the ActiveRecord object.
    def color_upcase
      self.color.upcase
    end

    # Accepts the stored value and returns an inversely modified version
    # to be used by the ActiveRecord attribute.
    def color_downcase(stored)
      stored.downcase
    end
end

在rails控制台中(注意大写的“red”):
irb> truck = Vehicle.create make: "Ford", model: "F150", year: 2015, color: "Red"

在rails数据库中(颜色在存储之前升级):
sqlite> SELECT * FROM `vehicles`;
1|Ford|F150|2015|RED|2015-06-24 16:07:33.176769|2015-06-24 16:07:33.176769

回到控制台(应用程序会看到一个降格版本):
irb> truck = Vehicle.find 1
irb> truck.color
=> red

最佳答案

(从评论转到回答)
在这种情况下,重写默认访问器可以解决问题。
更多信息和实现代码示例:http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord%3a%3aBase-label-Overwriting+default+accessors

关于ruby-on-rails - 如何在数据库之间转换ActiveRecord属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31031987/

10-10 00:47
查看更多