验证无效 - param丢失或值为空载波

时间:2014-12-18 10:29:32

标签: ruby-on-rails ruby-on-rails-4 carrierwave delayed-job

我已经找到了我的问题,但我找不到任何解决方案。

我的模型home包含以下属性:titlelogodescriptionkeywords

我正在使用carrierwave +延迟作业上传logo,上传工作(创建和更新)但是当文件/输入文件为空时我收到此错误:

ActionController::ParameterMissing in SettingsController#home_update_b
param is missing or the value is empty: home

Extracted source (around line #99): 

  def home_update_b_params
      params.require(:home).permit(:logo)
  end
end

SettingsController

def index
 ## get one record without params
 @home = Home.take 
end

def home_update_b
  @home = Home.find(params[:id])
   if @home.update(home_update_b_params)
     respond_to do |format|
      format.html { redirect_to setting_home_path, :notice => "Logo successfully updated" }
      format.json { head :no_content }
      end 
   else
     respond_to do |format|
      format.html { 
           flash[:alert] = "There's Something Wrong"
           render :action => :home
      }
      format.json { render json: @home.errors, status: :unprocessable_entity }
     end
   end
end

private

def home_update_b_params
 params.require(:home).permit(:logo)
end

我确信home模型已验证

class Home < ActiveRecord::Base
    mount_uploader :logo, LogoUploader
    after_save :enqueue

    validates_presence_of :logo
end

形式

<%= form_for(@home, :url => logo_update_path(@home), :html => { :class => "form-horizontal", :role => "form", :method => :put}) do |f| %>
  <div class="form-group">
    <%= f.label :logo, "Logo", :class => 'col-sm-3 control-label no-padding-right ace-file-input' %>
    <div class="col-sm-4">
            <%= f.file_field :logo, "data-file-input" => "easy" %>
    </div>
  </div>
  <div class="clearfix form-actions">
    <div class="col-md-offset-3 col-md-9">
      <%= f.submit %>
    </div>
  </div>
<% end %>

堆栈跟踪

Processing by SettingsController#home_update_b as HTML
  Parameters: {"utf8"=>"V", "authenticity_token"=>"gmXtbe31vfSPqM1N5taM1ge92nRvr
SpY91Y8vAlEBmc=", "commit"=>"Update Home", "id"=>"2"}
  ←[1m←[36mHome Load (0.0ms)←[0m  ←[1mSELECT  "homes".* FROM "homes"  WHERE "hom
es"."id" = $1 LIMIT 1←[0m  [["id", 2]]
Completed 400 Bad Request in 4ms

ActionController::ParameterMissing (param is missing or the value is empty: home
):
  app/controllers/settings_controller.rb:99:in `home_update_b_params'
  app/controllers/settings_controller.rb:60:in `home_update_b'

当我向表单添加另一个属性时(例如title),输入文件仍为空,它可以更新,但验证不适用于输入文件是空的。

FYI Rails 4.1.1和Ruby 1.9.3

1 个答案:

答案 0 :(得分:10)

如果您使用输入类型&#34;文件&#34;来接受来自用户的任何类型的文件。并且用户没有选择它,你不会在参数哈希中获得该字段的密钥。

在您的情况下,您只接受用户的徽标,如果该徽标为空,则主页键在您的参数哈希中不存在,因此{ {3}}方法抛出异常,因为它没有找到指定的密钥。

如果找不到指定的键,则可以使用require()方法代替require(),该方法可以返回空哈希作为默认值。像这样:

params.fetch(:home, {}).permit(:logo)