がスコープでユニークな検証を設定するようにしてください。ドキュメントはここ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
Thxを、仲間) – nuT707
ようこそ、仲間:) – retgoat