Uploading files in my gallery worked fine with Rails 3, but after upgrate I get exeption wrong argument type ActionDispatch::Http::UploadedFile (expected String)
in this line @reel.update_attributes(reels_params)
.
I don't use any gem for handle file uploading, because I need specific processing and store my files in db. After upgraded to rails 4, I added only 1 method to working with strong params in controller reels_params
.
Controller:
class Admin::ReelsController < AdminController
before_action :set_reel, only: [:show, :edit, :update, :destroy]
def update
respond_to do |format|
if @reel.update_attributes(reels_params)
format.html { redirect_to admin_reel_path(@reel), notice: t('helpers.messages.update_success') }
else
format.html { render action: "edit" }
end
end
end
...
private
def set_reel
@reel = Reel.find(params[:id])
end
def reels_params
params.require(:reel).permit!
end
end
View:
= form_for [:admin, @reel], :html => { :class => 'form-horizontal form-admin', :multipart => true } do |f|
.form-group
= f.label 'Gallery', :class => 'control-label col-sm-2'
.col-sm-10
- item.images.each do |img|
= f.fields_for :images, img do |img_f|
= img_f.text_field :title
= img_f.file_field :data, class: 'img_upload'
How to correct my code?
To break down this problem, I took the view down to only the single image-element
<%= form_tag({action: :update}, multipart: true, method: "patch") do %>
<%= file_field_tag 'image' %>
<div class="actions">
<%= submit_tag %>
</div>
<% end %>
with controller:
def update
@user.image = params[:image] <<------Fails on this line
respond_to do |format|
if @user.save ....
The Error is: "wrong argument type ActionDispatch::Http::UploadedFile (expected String)"
Looking here: http://api.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html ... we find the ".read" option, so I modified the controller to read:
def update
@user.image = params[:image].read <<------added the suffix here
respond_to do |format|
if @user.save ...
It works, and I can read the image back from the file OK. So, it appears we will need to isolate and save blobs separately, adding the ".read" suffix, and cannot save it in a group with other params until this BUG/(feature) is fixed.
来源:https://stackoverflow.com/questions/20603765/trouble-with-uploading-file-after-upgrating-rails-from-3-2-to-4