Rails 在部分内用逗号分隔数组项 [英] Rails separate array items with comma inside partial

查看:42
本文介绍了Rails 在部分内用逗号分隔数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 中在部分中创建逗号分隔列表的最优雅的方法是什么?

What is the most elegant way in Rails to create a comma-separated list inside a partial?

我最近发现您可以使用部分来遍历从另一个视图模板发送的集合.所以在我的视图模板中:

I've just recently discovered that you can use partials to iterate through a collection sent from another view template. So in the view template I have:

<% render @dvd.director %> 

然后在/view/directors/_director.html.erb:

Then in /view/directors/_director.html.erb:

<%= director.director %>

这实际上是这样的:

@dvd.director.each { |d| puts d.director }

现在,我知道我可以像这样使用 .join:

Now, I know I could use a .join like so:

<% @dvd.director.map { |t| t.director }.join(", ") %>

但是由于部分已经遍历数组中的每个条目,我怎样才能正确地分隔列表而不是最后一个(或单个)在末尾带有一个难看的逗号?

But since the partial already iterates through each entry in the array, how can I separate the lists properly and not have the last one (or a single one) with an ugly comma at the end?

很多条目只有一个导演,我只是想把那些不止一个导演的作品区分开来.我知道我可以手动完成所有这些(使用正常的非迭代部分并自己创建 .each 循环),但我正在尝试这样做,并学习 Rails 方式.

A lot of entries will have only one director, I just want to separate those that have more than one properly. I know I can do all this manually (using a normal, non-iterating partial and creating the .each loop myself), but am trying to do it, and learn, the Rails way.

谢谢.

编辑

为了更好地解释,@dvd.director 返回一个 ActiveRelation 对象,如下所示:

To try to explain a little better, @dvd.director returns an ActiveRelation object like so:

[#<Director id: 13, director: "Andrew Stanton">, #<Director id: 14, director: "Lee Unkrich">]

所以我不能只做 @dvd.director.join(', ')

除了

@dvd.director.each { |dir| dir.director }

因为那里我有同样的问题,我必须计算它们或确保它不是最后一项,然后在它们之间加上逗号,或者只提取导演姓名并将它们放入字符串或类似的东西中.如果我可以加入它会很棒.

Because there I have the same problem, I have to count them or make sure it's not the last item before I put a comma between them, or extract just the director names and put them into a string or something like that. If I could do a join it would be great.

推荐答案

Ruby 的 join 方法不会在数组中只有一个元素时添加分隔符.

Ruby's join method won't add the separator character if there is only a single element in the array.

对于任意大小的列表,您应该能够执行以下操作:

You should be able to do the following for a list of any size:

@dvd.director.map(&:director).join(", ")

这篇关于Rails 在部分内用逗号分隔数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆