Reputation: 41949
The way the models are associated in my Rails app, if I try to list the licenses that a user has with code like this
Licensed in <%= answer.user.licenses.map(&:state) %>
it'll print out like this
Licensed in ["New York"]
Since it's an array, I can remove the array brackets like this
<%= answer.user.licenses.map(&:state)[0] %>
and I get the result I want
Licensed in New York
However, if a user has more than one license (which is a possibility), that's not a good solution, as each license should be listed.
Therefore, I tried this
<% answer.user.licenses.map(&:state).each do |state| %>
<%= state %>
<% end %>
However, this won't add "smart" commas between licenses, smart meaning "add a comment where necessary but not at the end."
What should the code look like to achieve what I'm trying to do in this situation. I wasn't sure of the keywords I should google to figure this out.
Upvotes: 0
Views: 65
Reputation: 15056
In Rails, you can use to_sentence
. That will place a ,
between all of the elements and will place the word and
between the penultimate and ultimate words.
Upvotes: 4
Reputation: 20878
Try this
answer.user.licenses.map(&:state).join(',')
This will add ,
between each element of the array.
Upvotes: 4