我想建立一个for循环,但我这个错误。

undefined method `each' for nil:NilClass

那是 View 的一部分,它给了我错误:
    <% @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 %>

即使我已经在截止期限文件夹的索引 View 中使用了相同的循环,似乎也无法识别@deadlines。如何在首页 View 中使用相同的变量?

非常感谢!

这是 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

最佳答案

您的@deadlines现在为空,请将此@deadlines = Deadline.all用于您的首页 Controller 操作,并对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为空时,它将显示截止日期为空

07-24 09:20