rails中的if else语句 - 错误

时间:2014-11-20 02:08:23

标签: ruby-on-rails

谁能告诉我我做错了什么?

这是我的观点/ application.html.erb

<div class="table">
 <h1 align="center"><p class ="navbar-fouls" style="color:#48A5E3" >Recent Fouls</p></h1>
   <table align="center" style="width:100%">
     <tr>
        <% if Foul.any? %>
          <%= @foul.law %>
        <% else %>
          <p class="text-center" style="center">Game has not started yet.</p>
        <% end %>
     </tr>
   </table>

我收到错误

undefined method `law' for nil:NilClass

提取的来源(第79行):

76      <table align="center" style="width:100%">
77        <tr>
78           <% if Foul.any? %>
79             <%= @foul.law %>
80           <% else %>
81             <p class="text-center" style="center">Game has not started yet.</p>
82           <% end %>

我的犯规控制器中有这个 @foul明确定义时,我不明白为什么它会给我这个错误。

class FoulsController < ApplicationController
      before_action :authenticate_user!

  def index
    @fouls = Foul.all
  end

  def show
    @foul = Foul.find(params[:id])
  end

  def new
    @foul = Foul.new
  end


  def create
    @foul = Foul.new(fouls_params)
    if @foul.save
        redirect_to(:action => "index")
    else
        render("new")
    end
  end

  def edit
        @foul = Foul.find(params[:id])
  end

  def update
    @foul = Foul.find(params[:id])
        if @foul.update_attributes(fouls_params)
            redirect_to(:action => "show", :id => @foul.id)
        else
            render("index")
        end
  end

  def destroy
    foul = Foul.find(params[:id]).destroy
    redirect_to(:action => "index")
  end


  private
  def fouls_params
    params.require(:foul).permit(:law, :description)
  end
end`

2 个答案:

答案 0 :(得分:2)

期望您的控制器提供@foul实例变量。在这里,控制器设置@foul = nil(除非index@foul完全没有设置。)

答案 1 :(得分:0)

您应该检查Foul.any?

,而不是在views/application.html.erb中检查if @foul

Foul.any?调用您的数据库,但if @foul会检查变量实际设置的内容。

<% if @foul %>
   <%= @foul.law %>
<% else %>
   <p class="text-center" style="center">Game has not started yet.</p>
 <% end %>