1

How can I use with_options for conditional validation ?

My code is

with_options if: (AppUser::User.creator=="is_admin") do |admin|
  admin.validates :first_name, :presence => true
  admin.validates :last_name, :presence => true
end

I have already set creator method in application controller.

before_action :set_global_user

def set_global_user
  if current_admin
    AppUser::User.creator= "is_admin"
  elsif current_user
    AppUser::User.creator= "is_user"
  else
    AppUser::User.creator=nil
  end
end

but I am getting

undefined method `validate' for false:FalseClass

what is wrong with this code.

jon snow
  • 3,062
  • 1
  • 19
  • 31
Braham Shakti
  • 1,408
  • 4
  • 22
  • 39

1 Answers1

-1

because

(AppUser::User.creator == "is_admin")`

does not return an object but it is a boolean.

Try this (inside your model):

class User < ActiveRecord::Base
  with_options if: (AppUser::User.creator == "is_admin") do
    validates :first_name, presence: true
    validates :last_name, presence: true
  end
end

P.S: I recommend the use of the devise gem to manage user types like this: devise and multiple “user” models.

Community
  • 1
  • 1