Accessing Attributes in a Many-to-Many
Posted
by
tshauck
on Stack Overflow
See other posts from Stack Overflow
or by tshauck
Published on 2011-01-17T01:15:28Z
Indexed on
2011/01/17
1:53 UTC
Read the original article
Hit count: 453
ruby-on-rails
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 %>
© Stack Overflow or respective owner