Add number of records in belongs_to relationship in Rail app?
I have a Rails simple application that has two main models. A person model an开发者_开发问答d a gift model. Gifts belong to people, and people have many gifts.
I am currently (in the people index view) listing all people in the database with the following code:
<% for person in @people %>
<li><%= link_to h(person.name), person %></li>
<% end %>
What I would like to do, is have the number of gifts associated to a person next to their name in brackets. Example:
Danny McC (10)
Is there a built in way of doing this? Such as:
<%= @person.name.count =>
Is this possible?
Thanks,
Danny
Don't accept my answer, cause I don't want to steal Yannis' points, but his method can be rewritten like this:
def name_and_gifts_count
return "#{name} (#{gifts.count})"
end
Actually, I would leave out return
too. The last statement is automatically returned in Ruby.
def name_and_gifts_count
"#{name} (#{gifts.count})"
end
If you Person model has has_many :gifts
, in you model also add:
de name_and_gifts_count
name_and_gifts_count = name
name_and_gifts_count += '('
name_and_gifts_count += gifts.count.to_s
name_and_gifts_count += ')'
return name_and_gifts_count
end
then in your link, use:
<%= link_to h(person.name_and_gifts_count), person %>
精彩评论