1

I've got a simple one to many relationship between tasks and priorities.

class Task < ActiveRecord::Base
    attr_accessible :subject, :body, :priority_id, :company_id, :status_id, :user_ids
    has_and_belongs_to_many :users
    belongs_to :priority
    belongs_to :company
    belongs_to :status
end


class Priority < ActiveRecord::Base
    attr_accessible :name
    has_many :tasks
end

From my tasks/show.html.erb view

<%= @task.priority.name %>

This works.

However in my tasks/index.html.erb

<% @tasks.each do |task| %>
  <tr>
    <td><%= task.subject %></td>
    <td><%= task.body %></td>
    <td><%= task.priority.name %></td>
    <td><%= link_to 'Show', task %></td>
    <td><%= link_to 'Edit', edit_task_path(task) %></td>
    <td><%= link_to 'Destroy', task, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>

The call to task.priority.name does not work.

It throws a NoMethodError.

I'm guessing this is a really stupid newbie mistake but I can't for the life of me figure it out. It would have assumed that the Active Record magic would have filtered down into a look like this.

3 Answers 3

3

I guess your NoMethodError comes on nil:NilClass. Try:

  <%= task.priority.name if task.priority %>
1
  • excellent guess Christoph! many thanks - I guess when you are newbie you doubt your syntax and don't think of simple things like this :) much appreciated
    – Colm Troy
    May 22, 2012 at 9:38
0

Are you sure you have well created all the models and links with primary keys in your database? I think you link to a task with a priority id (prority_id) which doesn't exists.

Check your datas.

0

Given that there is no validation of the presence of priority in task, it's quite possible that you are calling "name" on nil. Validate the presence of priority (with validates_presence_of) or check it exists before printing it as Christoph says.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.