damoiser
damoiser

Reputation: 6238

Rails 3 validation with unique scope conditional

I have for example this code in my model validation:

  validates :fb_user_id, :uniqueness => {:scope => :campaign_id}

But can occurs that campaign_id has value -1 for different users, that raises the validate exception. It's possible to do something like this?

 validates :fb_user_id, :uniqueness => {:scope => :campaign_id}, if :campaign_id != -1

Can I put a if conditions inline in the validates statement or if not possible how can I do the trick?

Upvotes: 1

Views: 3198

Answers (1)

damoiser
damoiser

Reputation: 6238

Following the idea of MagicMarkker, I have found a solution:

validates :fb_user_id, :uniqueness => {:scope => :campaign_id}, :if => :valCampaign?

def valCampaign?
    if campaign_id == -1
        return false # skip the validation
    else 
        return true  # run the validation
    end
end

Upvotes: 6

Related Questions