You can use the conditions
option for this:
validates :phone_number, uniqueness: {scope: :call_type, conditions: -> { where(created_at: Time.now.month) }}
Check the available options for uniqueness validation
質問
In my rails 4 model, I have this:
class PhoneContact < ActiveRecord::Base
validates :phone_number, uniqueness: {scope: :call_type}
The idea is to ensure that each phone number on my PhoneContact
model is unique, by call_type.
I also want to go one step further and add a "and the model was created this month" to this. So, my phone_number
should be unique by call_type
and created_at == Time.now.month
.
How can I write that?
解決
You can use the conditions
option for this:
validates :phone_number, uniqueness: {scope: :call_type, conditions: -> { where(created_at: Time.now.month) }}
Check the available options for uniqueness validation