Janko
Janko

Reputation: 9335

Problems with conditional validation in ActiveRecord

I have to conditionally validate my User. After user registers, he can complete the rest of his profile. It's split into parts, so, for example, there is "Educational background" and "Professional background". Those parts consist of fields, which I have to validate (e.g. presence).

So, of course, these fields shouldn't be validated during registration, but only when the user tries to edit those fields. A natural idea would be to send a context parameter in the form, and do something like:

class User < ActiveRecord::Base
  attr_accessor :context

  with_options if: -> { |u| u.context == "educational" } do |s|
    s.validates :university_name, presence: true
    # ...
  end
end

But what if I also need to have conditional validation inside the block:

class User < ActiveRecord::Base
  attr_accessor :context

  with_options if: -> { |u| u.context == "educational" } do |s|
    s.validates :university_name, presence: true, if: :finished_university?
    # ...
  end
end

Which means that those to :ifs will clash. I could transform every :if in the block into an :unless, but this will hurt readability, and I really don't want that.

Is there another solution to this problem?

Upvotes: 0

Views: 981

Answers (2)

cthulhu
cthulhu

Reputation: 3726

If you need so many 'if' statements probably your model is flawed. Maybe you need to extract a new model from your User, define new resource and controller.

EDIT: This gem can be helpful: https://github.com/stevehodgkiss/validation-scopes

Upvotes: 2

benchwarmer
benchwarmer

Reputation: 2774

How about

validates :university_name, presence: true, if: :finished_university? && lambda {|u| u.context == "educational"}

Upvotes: 0

Related Questions