validate and update single attribute rails

后端 未结 5 1470
旧巷少年郎
旧巷少年郎 2021-02-08 22:55

I have the following in my user model

attr_accessible :avatar, :email

validates_presence_of :email
has_attached_file :avatar # paperclip

validates_attachment_s         


        
5条回答
  •  醉酒成梦
    2021-02-08 23:31

    I am assuming you need this, because you have a multi-step wizard, where you first upload the avatar and the e-mail is filled in later.

    To my knowledge, with your validations as they are, I see no good working solution. Either you validate all, or you update the avatar without validations. If it would be a simple attribute, you could check if the new value passes the validation seperately, and then update the model without validations (e.g. using update_attribute).

    I can suggest two possible alternative approaches:

    • either you make sure that the e-mail is always entered first, which I believe is not a bad solution. And then, with each save, the validation is met.
    • otherwise, change the validation. Why would you declare a validation on a model, if there are records in the database that do not meet the validation? That is very counter-intuitive.

    So I would propose something like this:

    validate :presence_of_email_after_upload_avatar
    
    def presence_of_email_after_upload_avatar
      # write some test, when the email should be present
      if avatar.present?
        errors.add(:email, "Email is required") unless email.present?
      end
    end
    

    Hope this helps.

提交回复
热议问题