Reputation: 11336
Inside my User.rb
model I validate presence of username
and name
validates_presence_of :username, :name
However, only the username
field is present on the form while name
is created using a before_validation
callback like this.
def set_username_as_name_if_empty
if self.username && self.username.present?
self.name = self.username if self.name && self.name.empty?
end
end
This work as long as the name
field is present on the form (as input or hidden doesn't matter).
My question is how can I achieve the same without having to add the name
field on the form? Sounds like a bit unnecessary to add it as a hidden value just because is required.
Any idea?
Upvotes: 0
Views: 180
Reputation: 54882
A way to simplify your validation method:
def set_username_as_name_if_empty
if name.blank?
name = username if username.present?
end
end
Because doing the following doesn't raise any error:
1.9.3p0 :038 > nil.present?
=> false
I don't understand exactly your question but if you meant
"Am I forced to have an input (even hidden) in my form to avoid a validation failed?"
I would say no, you don't need this input because you set the name
attribute before the validations.
Upvotes: 2