如何在数据库中只保存“完整”的唯一对象?

时间:2016-08-11 02:38:52

标签: ruby-on-rails activerecord

我有一个带有attrbutes的模型订单:name,:phone,:product_id

如何在数据库中仅保存订单的唯一对象 - 具有以下唯一组合:name,:phone和:product?

例如:

already in db: 
Order name: 'Bob', phone: '123', product_id: '4'

must not been saved: 
Order name: 'Bob', phone: '123', product_id: '4'

must be saved: 
Order name: 'Bob', phone: '123', product_id: '5'

must be saved: 
Order name: 'Bob', phone: '1234', product_id: '4'

1 个答案:

答案 0 :(得分:3)

尝试使用范围设置唯一验证。文档为here

class Order < ActiveRecord::Base
  validates :name, uniqueness: { scope: [:phone, :product_id], message: "Not UNIQ" }
end

结果如下:

[29] pry(main)> Order.all
  Order Load (0.3ms)  SELECT "orders".* FROM "orders"
=> [#<Order:0x007fd07cc6fd00 id: 1, name: "Bob", phone: "1234", product_id: 4, created_at: Thu, 11 Aug 2016 02:56:22 UTC +00:00, updated_at: Thu, 11 Aug 2016 02:56:22 UTC +00:00>]

[30] pry(main)> o1 = Order.new(name:"Bob", phone:"1234", product_id: 4)
=> #<Order:0x007fd07d5f3390 id: nil, name: "Bob", phone: "1234", product_id: 4, created_at: nil, updated_at: nil>

[31] pry(main)> o1.valid?
  Order Exists (0.4ms)  SELECT  1 AS one FROM "orders" WHERE ("orders"."name" = 'Bob' AND "orders"."phone" = '1234' AND "orders"."product_id" = 4) LIMIT 1
=> false

[32] pry(main)> o1.errors
=> #<ActiveModel::Errors:0x007fd07d65b580 @base=#<Order:0x007fd07d5f3390 id: nil, name: "Bob", phone: "1234", product_id: 4, created_at: nil, updated_at: nil>, @messages={:name=>["Not UNIQ"]}>

[33] pry(main)> o2 = Order.new(name:"Bob", phone:"12345", product_id: 4)
=> #<Order:0x007fd07cc7f3e0 id: nil, name: "Bob", phone: "12345", product_id: 4, created_at: nil, updated_at: nil>

[34] pry(main)> o2.valid?
  Order Exists (0.4ms)  SELECT  1 AS one FROM "orders" WHERE ("orders"."name" = 'Bob' AND "orders"."phone" = '12345' AND "orders"."product_id" = 4) LIMIT 1
=> true