【问题标题】:Trouble with uploading file after upgrating rails from 3.2 to 4将 rails 从 3.2 升级到 4 后无法上传文件
【发布时间】:2013-12-16 04:58:50
【问题描述】:

在我的库中上传文件在 Rails 3 上运行良好,但升级后我在这一行 @reel.update_attributes(reels_params) 中得到异常 wrong argument type ActionDispatch::Http::UploadedFile (expected String)。 我不使用任何 gem 来处理文件上传,因为我需要特定的处理并将我的文件存储在 db 中。升级到 rails 4 后,我只添加了一种方法来处理控制器 reels_params 中的强参数。

控制器:

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

查看:

= 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'

如何更正我的代码?

【问题讨论】:

    标签: ruby file-upload ruby-on-rails-4 strong-parameters


    【解决方案1】:

    为了解决这个问题,我将视图缩小到只有单个图像元素

    <%= form_tag({action: :update}, multipart: true,  method: "patch") do %>
        <%= file_field_tag 'image' %>
    
        <div class="actions">
          <%= submit_tag %>
        </div>
    
    <% end %>
    

    带控制器:

    def update
      @user.image = params[:image]  <<------Fails on this line
      respond_to do |format|
      if @user.save ....
    

    错误是: “错误的参数类型 ActionDispatch::Http::UploadedFile(预期字符串)”

    看这里: http://api.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html ...我们找到“.read”选项,所以我将控制器修改为读取:

    def update
      @user.image = params[:image].read  <<------added the suffix here
      respond_to do |format|
      if @user.save ... 
    

    它有效,我可以从文件中读取图像。因此,看来我们需要单独隔离和保存 blob,添加“.read”后缀,并且在修复此 BUG/(功能)之前无法将其保存在具有其他参数的组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2016-11-02
      • 2012-01-08
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多