ADMAT Bandara
ADMAT Bandara

Reputation: 61

How to validate Rails model based on a parameter?

I have User model, and need to validate phone number attribute based on the controller param.

class User < ActiveRecord::Base
  validates_presence_of :phone_number
end

This validation should validate phone_number in the Create action. Let's say the param I should check is

 params[:phone_number]

Upvotes: 1

Views: 2276

Answers (3)

ADMAT Bandara
ADMAT Bandara

Reputation: 61

I have tried many ways to complete this task,

  1. I used Inheritance - Created a sub class from the User class
  2. Call a method in the model from the controller to set the attribute and bind that attribute with the validation
  3. Use the context option

I guess the context option is the most reliable solution for this issue i faced. So here when i set the context as :interface the model validation will trigger only based on that value

Model - User.rb

class User < ActiveRecord::Base
  validates_presence_of :phone_number, on: :interface
end

Controller - users_controller.rb

@user = User.new(user_params)
@save_result = false
if params[:invitation_token] == nil
  save_result = @user.save(context: :interface)
else
  save_result = @user.save
end

If you use multiple options in ON:

  validates  :terms_and_conditions, acceptance: {accept: true}, on: [:create, :interface], unless: :child
  validates  :privacy_policy, acceptance: {accept: true}, on: [:create, :interface], unless: :child

Upvotes: 0

John Baker
John Baker

Reputation: 2398

validate :custom_validation, :on => :create

private
def custom_validation
   //whatever you want to check
end

Upvotes: 1

DevMasterAryan
DevMasterAryan

Reputation: 71

you can use before_save validation, in User model you can write

before_save :validate_phone_number
private
def validate_phome_number
   self.phone_number = /some regex/
end

In self.phone_number you will get controller params by default

Upvotes: 1

Related Questions