Ruby on rails 如何按字符串添加jbuilder属性
我正在使用rails和jBuilder在我的应用程序中提供JSON。我试图迭代各种颜色,仅当它们的值不是nil时才将它们添加到结果JSON中。这是我正在使用的,这是有效的,但我想学习如何公关 工作代码 非工作代码 “json[color]”部分是罪魁祸首,因为如果我只使用json.blah,它就可以工作。有什么建议吗?这可能会有帮助Ruby on rails 如何按字符串添加jbuilder属性,ruby-on-rails,json,string,hashmap,jbuilder,Ruby On Rails,Json,String,Hashmap,Jbuilder,我正在使用rails和jBuilder在我的应用程序中提供JSON。我试图迭代各种颜色,仅当它们的值不是nil时才将它们添加到结果JSON中。这是我正在使用的,这是有效的,但我想学习如何公关 工作代码 非工作代码 “json[color]”部分是罪魁祸首,因为如果我只使用json.blah,它就可以工作。有什么建议吗?这可能会有帮助 json.cost ["red", "white", "blue"] do |color| unless card["cost_" + color].nil?
json.cost ["red", "white", "blue"] do |color|
unless card["cost_" + color].nil?
json.set! color, card["cost_" + color]
end
end
你能试着用:红、:白、:蓝替换“红”、“白”、“蓝”吗?谢谢你的回复!这真的很接近,但这会为每种颜色创建一个对象,我希望有一个对象包含所有颜色。你能用你可能期望的响应更新你的答案吗?
json.cost do
["red", "white", "blue"].each { |color|
unless card["cost_" + color].nil?
json[color] card["cost_" + color]
end
}
end
json.cost ["red", "white", "blue"] do |color|
unless card["cost_" + color].nil?
json.set! color, card["cost_" + color]
end
end