Rails:nil的未定义方法`each':NilClass

时间:2018-03-09 11:17:33

标签: ruby-on-rails for-loop error-handling

我想构建一个for循环,但我是一个错误。

undefined method `each' for nil:NilClass

这是视图的一部分,它给了我错误:

    <% @deadlines.each do |deadline| %>
        <% if Time.now < deadline.deadline %>
            <%= form_for(current_user) do |f| %>
              <%= f.hidden_field :enrolled, :value => true %>
              <%= f.submit "Anmeldung bestätigen", class: "btn btn-primary" %>
            <% end %>
        <% end %>
    <% end %>

似乎无法识别@deadlines,即使我已在deadlines文件夹的Ind​​ex视图中使用了相同的循环。如何在主页视图中使用相同的变量?

非常感谢!

这是Controller,也许它还为您提供了一些信息:

class DeadlinesController < ApplicationController
  before_action :set_deadline, only: [:show, :edit, :update, :destroy]

  # GET /deadlines
  # GET /deadlines.json
  def index
    @deadlines = Deadline.all
  end

  # GET /deadlines/1
  # GET /deadlines/1.json
  def show
  end

  # GET /deadlines/new
  def new
    @deadline = Deadline.new
  end

  # GET /deadlines/1/edit
  def edit
  end

  # POST /deadlines
  # POST /deadlines.json
  def create
    @deadline = Deadline.new(deadline_params)

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

  # PATCH/PUT /deadlines/1
  # PATCH/PUT /deadlines/1.json
  def update
    if @deadline.update(deadline_params)
      flash[:success] = "Die Deadline wurde erfolgreich aktualisiert."
      redirect_to deadlines_path
    else
      flash[:error] = "Die Deadline wurde nicht aktualisiert."
    end
  end

  # DELETE /deadlines/1
  # DELETE /deadlines/1.json
  def destroy
    @deadline.destroy
    respond_to do |format|
      format.html { redirect_to deadlines_url, notice: 'Deadline was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_deadline
      @deadline = Deadline.find(params[:id])
    end

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

1 个答案:

答案 0 :(得分:1)

您的@deadlines现在为空,请将此@deadlines = Deadline.all用于您的主页控制器操作,并each阻止修改

<% if @deadlines.present? %>
    <% @deadlines.each do |deadline| %>
        <% if Time.now < deadline.deadline %>
            <%= form_for(current_user) do |f| %>
              <%= f.hidden_field :enrolled, :value => true %>
              <%= f.submit "Anmeldung bestätigen", class: "btn btn-primary" %>
            <% end %>
        <% end %>
    <% end %>
<% else %>
    Deadline is empty 
<% end %>

@deadlines为空时,它会显示截止日期为空