Reputation: 1009
I am doing a currently a project and I am using a devise.. In my sign up(using the devise) I have field named mobile number, when I click the sign up/submit button it will be save into my table but before it will save I concatenate the country code(+63. Example: I input 1234567891, in my table it will become like this +631234567891).
I used the before_save method/function but I am having a problem with it, whenever I click the sign in/confirm email/logout it will add another +63(so it will become +63+63....)..
Question: How can I prevent adding +63? It will only add the +63 during the sign-up
Model
before_save : add_country_code
validates :mobile_no, :presence => true,
:numericality => true,
:length => { :minimum => 10, :maximum => 10 }
def add_country_code
self.mobile_no = "+63" + self.mobile_no.to_s
end
Upvotes: 0
Views: 177
Reputation: 121010
def add_country_code
self.mobile_no = '+63' << self.mobile_no.to_s.gsub(/\A\+63/, '')
end
Upvotes: 0
Reputation: 1010
You can replace before_save
with before_create
. Whenever you sign in, devise updates some other columns like last_signed_in_at
, therefore before_save
is triggered.
But really you might want to check if you have prefixed the country code, in case the user wants to update the phone number.
Upvotes: 2
Reputation: 6603
before_save :add_country_code, unless: :mobile_no
mobile_no
is blank (which happens only at sign-up, or when updating your user information provided that there was no mobile_no
yet)Upvotes: 2
Reputation: 134
Your validates method is having length as 10 and that’s why while saving it is checking validation. Change validation as follows:
validates :mobile_no, presence: true,
numericality: true,
length: { is: 13 }
Keeping length 13 will allow you save +63 before saving. Hope this helps. Happy coding. :)
Upvotes: 0
Reputation: 30071
Try this one. Only update the mobile phone if the object is not persisted.
def add_country_code
self.mobile_no = "+63" + self.mobile_no.to_s unless persisted?
end
Upvotes: 1