Question

I have a such model

class Group < ActiveRecord::Base
  has_many :people
  has_one :leader
  attr_accessible :name
end

class Person < ActiveRecord::Base
  belongs_to :group
end

class Leader < Person
  belongs_to :group
  attr_accessible :first_name, :last_name
end

then I'm trying to draw a page of a group via this view

<p>
  <b>Name:</b>
  <%= @group.name %>
</p>

<p>
  <b>Leader:</b>
  <%= @leader.last_name %>
</p>

and get NoMethodError in Groups#show undefined method `last_name' for nil:NilClass

here is groups_controller

def show
  @group = Group.find(params[:id])
  @leader = @group.leader

What is wrong?

UPD this also doesn't work

<b>Leader:</b>
<%= @group.leader.last_name %>

I've really got stuck/ Please help!

Was it helpful?

Solution

The @group in your case doesn't have a leader. That variable is nil, so when you try to get the nil leaders name it errors.

You can enclose that portion of the page in an if block to make sure you don't get errors:

<% if @group.leader.nil? %>
  This group has no leader
<% else %>
  <%= @group.leader.last_name %>
<% end %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top