2

I have a nested resource like the following: user/1/photos/new

resources :users, only: [] do
  resources :photos, except: [:show]
end

My form_for is like the following:

= form_for([@user, @photo], html: { multipart: true }) do |f|

  .inputs
    = f.file_field :attached_photo

  .actions
    = f.submit :submit

I believe the problem I am having is with strong parameters:

   def photo_params
      params.require(:photo).permit(:title, :attached_photo)
    end

When I hit the submit button on the form I get the following error:

ActionController::ParameterMissing in PhotosController#create param not found: photo

I'm using Paperclip so in the model I have:

has_attached_file :attached_photo

Please advise.

Brian
  • 5,951
  • 14
  • 53
  • 77
  • What does your rails server output show for params posted? – jvperrin Oct 13 '13 at 16:49
  • If I add a text field for the title. Then params are like the following: "photo"=>{"title"=>""}, "commit"=>"submit", "painter_id"=>"1" It seems :attached_photo isn't being passed. – Brian Oct 13 '13 at 17:19
  • Does the file not get passed even when you upload it with the file field? I tested with a paperclip photo upload on one of my applications, and it only includes the parameter if a file is actually selected with the file field. – jvperrin Oct 13 '13 at 17:24
  • So the problem is how to ensure that a photo is attached – Brian Oct 13 '13 at 17:39
  • Which model to you have the `has_attached_file :attached_photo` code in? – jvperrin Oct 13 '13 at 17:43
  • It's in a Photo model. A User can have many Photos. – Brian Oct 13 '13 at 17:47

1 Answers1

2

If you want to make sure that a user uploads a photo when submitting this form, then you should add a validation on the Photo model like so:

validates_attachment_presence :attached_photo

Then if the user does not upload a photo, the form will re-render telling the user to upload a photo.

You will also want to use this strong parameters code to make sure you do not have an error if the photo param does not exist:

def photo_params
  params.require(:photo).permit(:title, :attached_photo) if params[:photo]
end
jvperrin
  • 3,368
  • 1
  • 23
  • 33