Reputation: 61
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
Reputation: 61
I have tried many ways to complete this task,
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
Reputation: 2398
validate :custom_validation, :on => :create
private
def custom_validation
//whatever you want to check
end
Upvotes: 1
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