0

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!

Maria
  • 79
  • 7

1 Answers1

0

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 %>
Matt
  • 13,948
  • 6
  • 44
  • 68
  • thanks. So '@leader = @group.leader' is not enough. How and where should I define the 'leader'? – Maria Aug 11 '13 at 00:30
  • `@leader = @group.leader` is fine, but that particular `group` in your test case hasn't had a `leader` assigned to it. In your view you can handle the `leader` being nil by enclosing that portion of the page in an if block, I've updated the answer to demonstrate. – Matt Aug 11 '13 at 08:42
  • Glad I could help :) Please accept an answer to close the question! – Matt Aug 11 '13 at 19:00