简体   繁体   中英

undefined method `…' for nil:NilClass in Rails ActiveRecord

I am not sure what's wrong with my code here:

class ZombieController < ApplicationController
  def index
    @zombies = Zombie.all

    respond_to do |format|
        #format.json {render json: @rotting_zombies}
        format.html
    end

  end
end


class Zombie < ActiveRecord::Base
  attr_accessible  :name, :rotting, :age
  has_many :tweets
  has_one :brain, dependent: :destroy
  scope :rotting, where(rotting: true)
  scope :fresh, where("age < 30")
  scope :recent,order('created_at desc').limit(3)

end

class Brain < ActiveRecord::Base
  attr_accessible :flavor, :status, :zombie_id
  belongs_to :zombie
end

On Zombie index view I render the zombie name with brain flavour as follows:

<h1>List</h1>
<table>
<tr>
<td>Name</td>
<td></td>
<td>Flavor</td>
</tr>


<% @zombies.each do |zombie|%>
<tr>
    <td><%= zombie.name %></td>
    <td><%= zombie.brain.flavor %></td>
</tr>
<% end %>




</table>

The errors I am receiving are undefined method flavor' for nil:NilClass.` what might be wrong here? As far as I know I correctly defined the relationship both for zombie and brain model.

For fixing the issue that Rails trying to fetch property from a nil object, there are few ways:

By checking nil in view

change your views/zombies/index.html.erb

<td><%= zombie.brain.flavor %></td>

to

<td><%= zombie.brain ? zombie.brain.flavor : "string with no brain here" %></td>

By delegate

In your models/zombie.rb

add delegate :flavor, :to=>:brain, :prefix=>true, :allow_nil=>true

And in your views/zombies/index , change the line as

<td><%= zombie.brain_flavor %></td>

By try()

Thanks @unnitallman

change your views/zombies/index.html.erb

<td><%= zombie.brain.flavor %></td>

to

<td><%= zombie.try(:brain).flavor %></td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM