I am building a photo gallery application that allows users to attach multiple photos to each of their galleries. I am using Paperclip to handle file uploads.
The below code works fine until [Upload] is clicked on the form with no file selected. As I understand it, it is getting stuck at the controller before it is handed over to the Photo
model to run it's presence, file-type and file-size validations.
The error received when clicking [Upload] with no file selected is:
"param is missing or the value is empty: photo"
Extracted source has photo#photo_params
line highlighted.
Gallery model:
class Gallery < ActiveRecord::Base
belongs_to :user
has_many :photos
end
Photo model:
class Photo < ActiveRecord::Base
belongs_to :user
belongs_to :gallery
has_attached_file :photo,
s3_permissions: :private
validates_attachment :photo,
presence: true,
content_type: {
content_type: [
"image/jpeg", # JPEG/JPG
"image/png" # PNG
] },
size: { in: 0..5.megabytes }
end
Controller action (photos#create):
def create
@photo = Photo.new(photo_params)
@photo.gallery_id = @gallery.id
@photo.user_id = current_user.id
if @photo.save
flash[:success] = "Photo successfully saved."
redirect_to gallery_path(@photo.gallery)
else
flash[:error] = "The photo upload failed! Make sure the file you're trying to upload is of a supported type (JPG, JPEG or PNG) and try again."
redirect_to gallery_path(@photo.gallery)
end
end
Strong Params (photos#photo_params):
def photo_params
params.require(:photo).permit(:photo)
end
Upload form:
<%= form_for Photo.new, url: gallery_photos_path(@gallery) do |f| %>
<%= f.label :photo %>
<%= f.file_field :photo %>
<%= f.submit "Upload" %>
<% end %>
I realise that using Model.new
in the form is probably not a best-practice but because the form is loaded as a partial on galleries#show view, it was the only way i could get it going.
I am also thinking that having the model named :photo
and the actual Paperclip attachment also named :photo
may also be causing an issue. Is this correct?
Does anyone know what's going on here?