在Rail应用程序中添加belongs_to关系中的记录数?

发布于 2024-09-28 21:04:21 字数 439 浏览 4 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小巷里的女流氓 2024-10-05 21:04:21

不要接受我的答案,因为我不想窃取 Yannis 的观点,但他的方法可以重写如下:

def name_and_gifts_count
  return "#{name} (#{gifts.count})"
end

实际上,我也会省略 return 。最后一条语句在 Ruby 中自动返回。

def name_and_gifts_count
  "#{name} (#{gifts.count})"
end

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
时常饿 2024-10-05 21:04:21

如果您的 Person 模型有 has_many :gifts,在您的模型中还添加:

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

然后在您的链接中使用:

<%= link_to h(person.name_and_gifts_count), person %>

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 %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文