I am implementing tag functionality and an article may have one to many tags. I am able to get tag values from db in this format
我正在实现标签功能,文章可能有一个到多个标签。我能够以这种格式从db获取标记值
["social network", "professional"]
I want output in this format
我想要这种格式的输出
"social network professional"
I want to convert an array into a string without ,
. Below is a code snippet which takes out values from db as an array.
我想将数组转换为字符串,而不是,。下面是一个代码片段,它将db中的值作为数组取出。
<%= article.tags.collect(&:name) %>
How can I convert this output into string value(s) with out any comma?
如何将此输出转换为字符串值而不使用任何逗号?
2 个解决方案
#1
12
Did you look at pluck
? This if very useful for if you want just one record from the db (in your case 'name'). You could use that to do this:
你看看采摘吗?如果您只需要db中的一条记录(在您的情况下为'name'),这非常有用。您可以使用它来执行此操作:
a = article.tags.pluck(:name)
To then output your article names separated by spaces do this:
然后输出以空格分隔的文章名称,执行以下操作:
a.join(" ")
For completeness sake, you can chain these methods (like you said in the comment below) like this:
为了完整起见,您可以链接这些方法(就像您在下面的评论中所说的那样),如下所示:
article.tags.pluck(:name).join(" ")
#2
0
I got two solutions which are below:
我有两个解决方案如下:
<%= article.tags.collect(&:name).join(" ")%>
<%= article.tags.pluck(:name).join(" ") %> - by yossarian.
#1
12
Did you look at pluck
? This if very useful for if you want just one record from the db (in your case 'name'). You could use that to do this:
你看看采摘吗?如果您只需要db中的一条记录(在您的情况下为'name'),这非常有用。您可以使用它来执行此操作:
a = article.tags.pluck(:name)
To then output your article names separated by spaces do this:
然后输出以空格分隔的文章名称,执行以下操作:
a.join(" ")
For completeness sake, you can chain these methods (like you said in the comment below) like this:
为了完整起见,您可以链接这些方法(就像您在下面的评论中所说的那样),如下所示:
article.tags.pluck(:name).join(" ")
#2
0
I got two solutions which are below:
我有两个解决方案如下:
<%= article.tags.collect(&:name).join(" ")%>
<%= article.tags.pluck(:name).join(" ") %> - by yossarian.