4

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

["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.

<%= article.tags.collect(&:name) %>

How can I convert this output into string value(s) with out any comma?

3 Answers 3

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:

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(" ")
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I know, the difference however is on which level both operate. pluck operates on the db level and collect on the array. To see this in action, check your tail -f /log/development.log for both cases. With the collect method the query returns all fields and then collects the fields you want, with pluck, only the db parameter will be retrieved.
0

I got two solutions which are below:

<%= article.tags.collect(&:name).join(" ")%>
<%= article.tags.pluck(:name).join(" ") %> - by yossarian.

Comments

-1

["social network", "professional"].join(",")

"social network,professional"

or if you don't want the comma

["social network", "professional"].join(" ")

"social network professional"

1 Comment

.join(" ") has already been mentioned in both existing answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.