ruby-on-rails - 有没有办法用两个数据库列来支持新的 Rails 5 属性

标签 ruby-on-rails postgresql ruby-on-rails-5

我正在考虑使用新的 Rails 5 attributes API对于自定义数据类型,理想情况下将数据存储在两个数据库列中,一个用于数据 value,一个用于一些额外的 type 信息。

Attributes API 似乎设计为仅使用一个数据库列,我想知道我是否缺少使用两个列的方法。

例子

设想一个 Money 对象,其中一个 decimalinteger 列用于值,一个 string 列用于货币代码。我会传入我的自定义货币对象,将其存储两列,然后读回它会将两列组合成一个货币对象。

我考虑过将值和货币序列化到单个 Postgres JSON 列中,但我希望能够执行快速 SQL SUM 查询并仅对值列进行排序,所以这不会看起来不太理想。

提前感谢您的任何见解。

最佳答案

我猜你正在考虑创建一个 ValueObject在您的模型中。

ActiveRecord::Aggregations为了那个原因。示例:

class Customer < ActiveRecord::Base
  composed_of :balance, class_name: "Money", mapping: %w(balance amount)
end

class Money
  include Comparable
  attr_reader :amount, :currency
  EXCHANGE_RATES = { "USD_TO_DKK" => 6 }

  def initialize(amount, currency = "USD")
    @amount, @currency = amount, currency
  end

  def exchange_to(other_currency)
    exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
    Money.new(exchanged_amount, other_currency)
  end

  def ==(other_money)
    amount == other_money.amount && currency == other_money.currency
  end

  def <=>(other_money)
    if currency == other_money.currency
      amount <=> other_money.amount
    else
      amount <=> other_money.exchange_to(currency).amount
    end
  end
end

关于ruby-on-rails - 有没有办法用两个数据库列来支持新的 Rails 5 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37551832/

相关文章:

ruby-on-rails - rails 3 : alias_attribute and Unkown column error

ruby-on-rails - 对多个地址进行地理编码

javascript - 在 Rails 中存储前端功能?

ruby-on-rails - 在 rails 中具有关联的 fixture

ruby-on-rails - Rails 5 将环境变量读取为 YAML 文件中的字符串

ruby-on-rails - 某些操作需要某些参数

Python - Postgresql varchar 的无效字节序列 - 奇怪的行为

ruby-on-rails - Rails 迁移以添加索引到 2 列之间的差异

regex - 替换正则表达式在 postgresql 中不起作用

Javascript 未在 Rails View 部分中执行