0

I have two separate forms for a profile picture and the rest of the profile information. Both forms, however, correspond to the profile model. For several of the profile attributes, I have validations like:

validates :title, presence: true
validates :zip_code, presence: true

The problem is that the validations are checked when someone tried to upload an image, which I don't want. That being said, I also have an image validator, so I don't want to avoid validation completely, just certain ones. I was thinking of trying to access the params hash in the model, but I can't figure out how and I'm pretty certain its a bad idea anyway. How can I make the right validation conditions? I already tried this:

validates :title, presence: true, :unless => :picture_exists?

def picture_exists?
    if self.pic
        puts 'yo pic exist'
        return true
    else
        puts 'yo no pic'
        return false
    end
end

but it does not work because it checks whether or not the profile has a picture, not whether the params have a picture. So if someone had already saved a picture, they would be able to bypass the validations which I don't want. I want the validations to be bypassed when they are not using the picture submit form.

Philip7899
  • 4,599
  • 4
  • 55
  • 114

1 Answers1

0

You can approach the issue in several ways:

1.- Skip all validations in your controller action (and validate manually, I guess)

save(validate: false) (source)

2.- Use a condition that you set manually before saving like this.

3.- Use a custom validation that stops all other validations from triggering if passes.

Maybe you can come up with more.

PS: Why would you expect your user to bypass the other validations before setting the profile picture?

GL & HF

Community
  • 1
  • 1
rlecaro2
  • 755
  • 7
  • 14
  • Thanks, number 3 could work, but is there a way to actually do that? I'm not sure I understand your PS question? – Philip7899 Jan 16 '14 at 19:38
  • I think number 2 is better (and closely related to 3). Maybe this can shed some light: http://stackoverflow.com/questions/8881712/skip-certain-validation-method-in-model – rlecaro2 Jan 17 '14 at 12:56
  • @Philip7899 About the PS I ask why would all the other validations trigger errors? Does your app flow considers the use case of setting a profile picture even with other fields empty (or whatever you're validating)? – rlecaro2 Jan 17 '14 at 12:58
  • the stack overflow question you posted looks like what i need. The only problem is i can't do "new_car=Car.new(skip_method_2: true)" because i already do @profile = Profile.new(profile_params) , So how can i pass "skip_method: true"? – Philip7899 Jan 20 '14 at 22:15
  • @Philip7899 you can append all the keys you want to a hash. I'm not quite sure but `profile_params[:skip_method] = true` should do the trick. Check out ruby hash docs: http://ruby-doc.org/core-2.1.0/Hash.html – rlecaro2 Jan 20 '14 at 23:28