Reputation: 1947
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.
Upvotes: 1
Views: 314
Reputation: 1156
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.
Upvotes: 0
Reputation: 4157
I guess your NoMethodError comes on nil:NilClass. Try:
<%= task.priority.name if task.priority %>
Upvotes: 3
Reputation: 6660
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.
Upvotes: 0