开发者

Rails loop and .join method

开发者 https://www.devze.com 2023-02-28 03:26 出处:网络
I have project and city table, and many-to-many relation between. I want i开发者_JAVA百科n html to get list of cities names, divided with \", \".

I have project and city table, and many-to-many relation between.

I want i开发者_JAVA百科n html to get list of cities names, divided with ", ".

I tried with this:

<%= @project.cities(&:name).join(", ") %>

But I get (I think) object like this:

#<City:0x103886748>

Where I made a mistake? :|

P.S. Explanation:

I have @project that have one or more cities. I want to loop through cities and print names like this: New York, Boston, Belgrade (without comma on the end).


You've forgot map here

<%= @project.cities.map(&:name).join(", ") %>


There is also a very cool built in helper to do that.

to_sentence

http://api.rubyonrails.org/classes/Array.html#method-i-to_sentence

<%= @project.cities(&:name).map.to_sentence %>
0

精彩评论

暂无评论...
验证码 换一张
取 消