Chapsterj
Chapsterj

Reputation: 6635

carrierwave exception for upload

I'm using carrierwave to upload image files. I basically have a form field "_form.html.erb" that has a title, description, image and category that is submitted to the DB. What I want to do is if a category is != to "social" then check for image presence but if it is equal to social then go ahead and submit to DB without an image. Right now I get a error when submitting "Image can't be blank". I thought this error might be coming from the validates_presence_of :image line that I have in my model but not sure about this. So I tried to wrap it in a if statement block, but I'm still getting it. Does anyone know how I get around what I'm trying to do.

if :category != "social" 
    validates_presence_of :image
  end

Upvotes: 0

Views: 309

Answers (1)

deefour
deefour

Reputation: 35370

Use a Proc with the :if option on the validator.

validates :image, presence: true, if: Proc.new { |a| a.category != "social" }

Recommended Reading: http://guides.rubyonrails.org/active_record_validations_callbacks.html#using-a-proc-with-if-and-unless

Upvotes: 3

Related Questions