I am using the paperclip gem for image uploads and am having trouble getting it to display an error message when my :photo
atrribute is not present.
My model is Image.rb:
validates_attachment :photo, :presence => true,
:content_type => { :content_type => ["image/jpeg", "image/png"], :message => "must be a jpeg or png" },
:size => { :in => 0..1.megabytes, :message => "must be less than 1 MB" }
My controller create action:
def create
@images = Image.all
@image = Image.new(image_params)
if @image.save
redirect_to new_image_url, notice: 'Image uploaded.'
else
@image.errors.delete(:photo)
render :new
end
end
When I submit the form without attaching an image, it raises an exception and shows the page:
ActionController::ParameterMissing in ImagesController#create
param is missing or the value is empty: image
def image_params
params.require(:image).permit(:photo)
end
I would except it to pass an error message to the errors hash like the rest of them, hence just displaying an error to full_messages
. But it is not doing that.
Any idea what I am doing wrong?
Update: Adding form to upload
<%= simple_form_for @image, html: { multipart: true } do |f| %>
<% if @image.errors.any? %>
<div class="panel panel-default border-danger">
<div class="panel-heading background-color-danger"><%= pluralize(@image.errors.count, "error") %>:</div>
<div class="panel-body">
<ul class="list-unstyled">
<% @image.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<div class="form-group">
<%= f.file_field :photo, error: false, input_html: { class: "form-control" } %>
</div>
<hr />
<div class="form-group">
<%= f.button :submit, "Upload", class: "btn btn-default" %>
</div>
<% end %>
** I realize the error: false
doesn't look good, but it just disables the simple_form inline errors. That isn't the problem.
UPDATED SOLUTION:
Based on the accepted answer, here is my new create action and strong parameters which I've used to form a viable solution to this problem.
ImagesController.rb #create
# POST /images
def create
@images = Image.all
@image = Image.new(image_params)
if params[:image]
if @image.save
redirect_to new_image_path, notice: 'Photo uploaded.'
else
@image.errors.delete(:photo)
render :new
end
else
redirect_to new_image_path, alert: 'Photo cannot be blank.'
end
end
Strong params
def image_params
params.require(:image).permit(:photo) if params[:image]
end