ActiveRecord has_one / has_many在同一个Model /表中

时间:2014-08-26 16:19:04

标签: ruby-on-rails model rails-activerecord

我正在试图找出构建模型的最佳方法。每个用户可以有很多余额,但我想为每个用户强制执行每种货币的一种余额。应用程序控制记录生成,所以这可能是矫枉过正。然而,这个问题困扰着我,所以我想我会问社区。

如果这样做有意义,最好的方法是什么呢?

到目前为止我的迁移:

class CreateBalances < ActiveRecord::Migration
  def change
    create_table :balances do |t|
      t.decimal :amount
      t.integer :currency, default: 0, null: false  # this will be an enum in the model
      t.references :user, index: true

      t.timestamps
    end
  end
end

TL; DR:其中一个:每个货币:用户

1 个答案:

答案 0 :(得分:0)

在您的余额模型中尝试此操作:

validates :currency, :uniqueness => true, :scope => user_id

我认为这说(而且我可能错了,所以请一点儿拿这个),“确保这种类型的货币只存在一次给这个用户。”如果做不到这一点,您也可以尝试自定义验证:

validates :unique_currency_balance_per_user

def unique_currency_balance_per_user
  Balance.where('id != ?', id)
         .where(:currency => currency, :user_id => user_id)
         .present?
end

也可能存在数据库级限制,但我还没有意识到这些。

相关问题