简体   繁体   中英

validates_presence_of attribute that is not present on form

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM