views:

26

answers:

2

Hi Everyone?

I have a Rails simple application that has two main models. A person model and 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

+1  A: 

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 %>
Yannis
Great, that worked perfectly. Thanks!
dannymcc
You can make it much shorter. This looks quite ugly IMO... `return "#{name} (#{gifts.count})"`
captaintokyo
@captaintokyo - within the person model again, or within the view?
dannymcc
In the model: just replace everything that is in the method above with: `return "#{name} (#{gifts.count})"`. Functionality is exactly the same. I just think this looks much better.
captaintokyo
I get a syntax error if I add: `def name_and_gifts_count` `return "#{name} (#{gifts.count})` `end`
dannymcc
You are missing a double quote... I will add it as an answer, so it's more clear.
captaintokyo
I frequently use this way when building string in order to easily add some logic. For example you can do something like `name_and_gifts_count += gifts.count > 0 ? gifts.count.to_s : 'no picture'` or even replace the 'no picture' string by a link toward the form that allows the upload of pictures…
Yannis
Everyone is entitled to their opinion... in your last example I would just use an if statement: `if gifts.count > 0` `"#{name} (#{gifts.count})"` `else` `"#{name} (no gifts)"` `end`
captaintokyo
+2  A: 

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
captaintokyo
That is much tidier, nice one - thanks!
dannymcc