Reputation: 55
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.
Upvotes: 0
Views: 1858
Reputation: 2785
For fixing the issue that Rails trying to fetch property from a nil
object, there are few ways:
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>
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>
Thanks @unnitallman
change your views/zombies/index.html.erb
<td><%= zombie.brain.flavor %></td>
to
<td><%= zombie.try(:brain).flavor %></td>
Upvotes: 2