Search code examples
ruby-on-railsstrong-parameters

Rails 4 Strong Parameters Nested Resource


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.


Solution

  • 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