Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top