这个错误是什么意思表单中的第一个参数在RoR中不能包含nil或为空

时间:2017-09-28 00:31:06

标签: ruby-on-rails

我有这个错误表单中的第一个参数不能包含nil或为空

在下一个代码中并不知道如何解决。我检查了其他类似的问题,但没有运气。

我也共享控制器,这似乎是问题,但仍然不知道如何解决它

<%= form_for @upload do |f| %>
  <% if @upload.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@upload.errors.count, "error") %> prohibited this document from being saved:</h2>

      <ul>
        <% @upload.errors.full_messages.each do |message| %>
            <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.file_field :file %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

控制器: 这就是我的应用程序中的东西。但我没有看到这个问题。

class UploadsController < ApplicationController
  before_action :upload_params, only: [:show, :edit, :update, :destroy]

  def index
    @uploads = Upload.all
  end

  def show
    send_data(@upload.file_contents,
              type: @upload.content_type,
              filename: @upload.filename)
  end

  def new
    @upload = Upload.new
  end

  def edit
  end

  def create
    @upload = Upload.new(upload_params)

    respond_to do |format|
      if @upload.save
        format.html { redirect_to upload_path, notice: 'Document was successfully created.' }
        format.json { render :show, status: :created, location: @upload }
      else
        format.html { render :new, notice: 'Wrong file' }
        format.json { render json: @upload.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @upload.update(upload_params)
        format.html { redirect_to @upload, notice: 'Document was successfully updated.' }
        format.json { render :show, status: :ok, location: @upload }
      else
        format.html { render :edit }
        format.json { render json: @upload.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @upload.destroy
    respond_to do |format|
      format.html { redirect_to uploads_url, notice: 'Document was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

  def set_upload
    @upload = Upload.find(params[:id])
  end

  def upload_params
    params.require(:upload).permit(:file)
  end
end

1 个答案:

答案 0 :(得分:0)

从我说的错误中可以看出这一点。 @upload对象不得为nil。请确保在渲染此视图之前启动该对象(通常在控制器中)。

查看您的控制器代码,请更改before_action以致电set_upload

before_action :set_upload, only: [:show, :edit, :update, :destroy]