I'm having trouble with carrierwave and rails 4 strong parameters. I have a very simple model with a carrier wave upload button. I'd like to show an error message if someone submits the upload form without choosing a file to upload.
Right now, I get a param not found:photo
error with this message:
# Never trust parameters from the scary internet, only allow the white list through.
def photo_params
params.require(:photo).permit(:image)
end
This error is happening because Rails 4's strong parameters is requiring that the image parameter be present to submit the form, but it's not there because the user hasn't selected an image.
I can't figure out a way to work around this and have it redirect to the same action and display an error message.
Is there a way to do this with strong parameters?
Here's the development log when I try to use the form without a photo selected: https://gist.github.com/leemcalilly/09b6166ce1af6ca6c833
And here's the development log when I choose a photo and it uploads successfully: https://gist.github.com/leemcalilly/1f1e584f56aef15e7af1
Other relevant files: * models/photo.rb - https://gist.github.com/leemcalilly/95c54a5df4e4ee6518da * controllers/photos_controller.rb - https://gist.github.com/leemcalilly/c0723e6dc5478b0f914d * uploaders/image_uploader.rb - https://gist.github.com/leemcalilly/5e43f6524734991773ae * views/photos/index.html.erb - https://gist.github.com/leemcalilly/a8c4c808e5e8a802933b * views/photos/_form.html.erb - https://gist.github.com/leemcalilly/cd0fd518c1b47d9bfb62 * initializers/carrierwaver.rb - https://gist.github.com/leemcalilly/49e04fa1dda891dd108b
The rails guides provides the solution. Use the fetch
method in the same way as the require
method. Note a second argument: it supplies the default value. So, if the params[:photo]
would not be found, the default value (an empty hash, as of the example below) will be returned:
params.fetch(:photo, {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With