在Rail应用程序中添加belongs_to关系中的记录数?
我有一个 Rails 简单应用程序,有两个主要模型。人物模型和礼物模型。礼物属于人,而人有很多礼物。
我目前(在人员索引视图中)使用以下代码列出数据库中的所有人员:
<% for person in @people %>
<li><%= link_to h(person.name), person %></li>
<% end %>
我想做的是将与某人姓名旁边的礼物相关的数量放在括号中。示例:
Danny McC (10)
有内置的方法可以做到这一点吗?如:
<%= @person.name.count =>
这可能吗?
谢谢,
丹尼
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要接受我的答案,因为我不想窃取 Yannis 的观点,但他的方法可以重写如下:
实际上,我也会省略
return
。最后一条语句在 Ruby 中自动返回。Don't accept my answer, cause I don't want to steal Yannis' points, but his method can be rewritten like this:
Actually, I would leave out
return
too. The last statement is automatically returned in Ruby.如果您的 Person 模型有
has_many :gifts
,在您的模型中还添加:然后在您的链接中使用:
If you Person model has
has_many :gifts
, in you model also add:then in your link, use: