Accessing Attributes in a Many-to-Many
- by tshauck
Hi,
I have a rails app and I'd like to be able to do something like
task.labels.first.label_name to get the label name of a task. However, I get an undefined method label_name. I did a t = Task.first; t.labels.first.label_name in the console, and that worked so I'm not sure what's going on. Here's the models then the locations of the error:
class Categorization < ActiveRecord::Base
belongs_to :label
belongs_to :task
end
class Label < ActiveRecord::Base
attr_accessible :label_name
has_many :categorizations
has_many :tasks, :through => :categorizations
end
class Task < ActiveRecord::Base
attr_accessible :task
has_many :categorizations
has_many :labels, :through => :categorizations
end
The error is in the index
<% for task in @tasks %>
<tr>
<td><%= task.task %></td>
<td><%= task.labels.first.label_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 %