【问题标题】:Activerecord data validationsActiverecord 数据验证
【发布时间】:2015-11-19 03:37:00
【问题描述】:

我有三个模型

BidPrinterOrder

一台打印机可以有多个出价,但一个订单只能有一个。

我无法验证确切的情况,a printer can have many bids, but only one bid per order

是否有任何内置于 ActiveModel 或 ActiveRecord 的验证?如果没有关于如何确保打印机每个订单只能有一个投标的任何想法?

class Bid < ActiveRecord::Base
  belongs_to :printer
end

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :bids
end

class Printer < ActiveRecord::Base
  has_many :orders, through: :bids
  has_many :bids
end

【问题讨论】:

标签: ruby-on-rails ruby activerecord activemodel


【解决方案1】:

可能有一种更巧妙的方法可以做到这一点,但您总是可以将一个块传递给validate。也许是这样的?

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :bids
end

class Bid < ActiveRecord::Base
  belongs_to :printer
end

class Printer < ActiveRecord::Base
  has_many :orders, through: :bids
  has_many :bids

  validate do
    order_ids = orders.pluck(:bid_id)
    dups = order_ids.detect{ |id| order_ids.count(id) > 1 }
    errors.add(:bids, 'Only one order per bid per printer') if dups.any?
  end
end

【讨论】:

    【解决方案2】:

    一台打印机可以有多个出价,但每个订单只有一个出价

    换句话说,对(order_id,printer_id)的值在bids表中必须是唯一的,对吧?所以你只需要验证Bid模型中(order_id,printer_id)的唯一性就好了

    validates :order_id, uniqueness: { scope: :printer_id }
    

    好的,为了澄清我的回答,我有一个 bids 表示例。

    +--------+----------+------------+
    | bid_id | order_id | printer_id |
    +--------+----------+------------+
    |      1 |        1 |          1 |
    |      2 |        1 |          2 |
    |      3 |        2 |          2 |
    |      4 |        2 |          3 |
    +--------+----------+------------+
    

    一切都好:打印机每个订单都有一个投标。但是如果我们在表中添加类似 [5, 2, 3] 的记录会发生什么?带有printer_id = 3 的打印机将有2 个出价(带有bid_id = 4,5)!条件完全相同,对 (order_id, printer_id) 的值在这里不是唯一的!

    +--------+----------+------------+
    | bid_id | order_id | printer_id |
    +--------+----------+------------+
    |      4 |        2 |          3 |
    |      5 |        2 |          3 |
    +--------+----------+------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-17
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 2014-05-11
      相关资源
      最近更新 更多