nee*_*raj 7 loops ruby-on-rails string-concatenation
我是RoR的新手.我试图在googling中找到一种方法来连接Controller中循环中的字符串.
assets = Asset.where({ :current_status => ["active"] }).all
assets.each do |a|
string = string + ":"+ a.movie_title
end
Run Code Online (Sandbox Code Playgroud)
我想将属性"movie_title"连接为一个冒号分隔的字符串.
但我得到错误
undefined method `+' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
Jak*_*b S 17
最简单的方法可能是:
string = assets.collect(&:movie_title).join(':')
Run Code Online (Sandbox Code Playgroud)
collect(&:movie_title)与collect { |asset| asset.movie_title }返回电影标题数组的相同.join(':')使用Array中的值分隔创建一个String :.
试试这个
assets = Asset.where({ :current_status => ["active"] }).all
string = ""
if assets.present?
assets.each do |a|
string = string + ":"+ a.movie_title
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49884 次 |
| 最近记录: |