Rails 4 Strong Parameters Nested Resource

℡╲_俬逩灬. 提交于 2020-01-04 13:46:43

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/19347619/rails-4-strong-parameters-nested-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!