【问题标题】:ActiveRecord has_one / has_many within same Model/tableActiveRecord has_one / has_many 在同一个模型/表中
【发布时间】:2014-08-26 16:19:04
【问题描述】:

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

如果这样做有意义,那么构建它的最佳方法是什么?

到目前为止我的迁移:

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:每个 :currency per :user 之一

【问题讨论】:

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


    【解决方案1】:

    在你的 Balance 模型中试试这个:

    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
    

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

    【讨论】:

    • 谢谢,会试一试并通知您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多