2016-08-11 6 views
1

人。どのようにデータベースに保存する "完全な"一意のオブジェクト?

私はattrbutesとモデルの受注があります、電話:名前を、データベース内の秩序の唯一のユニークなオブジェクト保存方法

PRODUCT_ID - のユニークな組み合わせを持つ:名前:電話と:製品を?例では

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' 

答えて

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 
+0

Thxを、仲間) – nuT707

+0

ようこそ、仲間:) – retgoat