Rails 4强参数param not found with carrierwave

我遇到了载波和轨道4强参数的问题。 我有一个非常简单的模型,带有载波上传按钮。 如果有人提交上传表单而没有选择要上传的文件,我想显示错误消息。

现在,我得到一个param not found:photoparam not found:photo此消息的param not found:photo错误:

  # Never trust parameters from the scary internet, only allow the white list through. def photo_params params.require(:photo).permit(:image) end 

发生此错误是因为Rails 4的强参数要求提供图像参数以提交表单,但由于用户未选择图像,因此不存在。

我无法找到解决此问题的方法,并将其重定向到相同的操作并显示错误消息。

有没有办法用强参数做到这一点?

当我尝试使用没有选择照片的表单时,这是开发日志: https : //gist.github.com/leemcalilly/09b6166ce1af6ca6c833

当我选择照片并成功上传时,这是开发日志: https : //gist.github.com/leemcalilly/1f1e584f56aef15e7af1

其他相关文件:* models / photo.rb – https://gist.github.com/leemcalilly/95c54a5df4e4ee6518da * controllers / photos_controller.rb – https://gist.github.com/leemcalilly/c0723e6dc5478b0f914d * uploaders / image_uploader.rb – https://gist.github.com/leemcalilly/5e43f6524734991773ae * views / photos / index.html.erb – https://gist.github.com/leemcalilly/a8c4c808e5e8a802933b * views / photos / _form.html.erb – https ://gist.github.com/leemcalilly/cd0fd518c1b47d9bfb62 * initializers / carrierwaver.rb – https://gist.github.com/leemcalilly/49e04fa1dda891dd108b

导轨提供解决方案 。 以与require方法相同的方式使用fetch方法。 请注意第二个参数:它提供默认值。 因此,如果找不到params[:photo] ,将返回默认值(空哈希,如下例所示)

 params.fetch(:photo, {}) 

对不起发现这有点晚了,好了,现在看看你的表单代码看起来像这样

 <%= form_for @photo, :html => {:multipart => true} do |f| %> <% if @photo.errors.any? %> 

<%= pluralize(@photo.errors.count, "error") %> prohibited this photo from being saved:

    <% @photo.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %>
Upload a Photo
<%= f.file_field :image %>
<%= f.submit "Upload Photo", :class => "btn btn-small" %> <% end %>

现在这不是railscarrierwavestrong_parameter的问题,这是html工作原理。 就像这样,如果您有file输入并且nothing附加nothing内容,则不会通过HTMLnamevalue对发送到服务器,例如checkboxdisabled字段

现在,因为您的表单只包含<%= f.file_field :image %>并且它不包含任何其他字段(照片模型的属性)

因此,当file输入does not包含任何附件时,不会构造photo哈希

这在您的日志中也很明显

参数(未附加附件)=>

 {"utf8"=>"✓", "authenticity_token"=>"IvOieBvxdA6qzVKrt1dYBuCXlt+uuWCyWjUAuTK0XEU=", "commit"=>"Upload Photo"} 

参数(附带附件)=>

  {"utf8"=>"✓", "authenticity_token"=>"I4O0w+Wk8nJaD6HJRSC+FfuAip5NVE6TkCUFDEN+sW0=", "photo"=>{"image"=>#, @original_filename="bag.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"bag.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Upload Photo"} 

现在你可以看到两者之间的差异,并且差异是你的错误的原因,因为在

第一个案例

params[:photo].present? =>假

第二个案例

params[:photo].present? =>是的

因此,当你这样做时, params.require(:photo).permit(:image)代码会抛出错误

因为该行提到了.require(:photo) ,它not存在于params

解:-

也许你可以做这样的事情

  def photo_params if params[:photo].present? params.require(:photo).permit(:image) end end 

结论: –

这不是任何人的错,因为这是HTML如何工作,如果no附件no name=value对提交给服务器,因为没有发送到服务器的photo参数因此哈希是没有他们因此强参数抛出错误

希望这有帮助