Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何按字符串添加jbuilder属性_Ruby On Rails_Json_String_Hashmap_Jbuilder - Fatal编程技术网

Ruby on rails 如何按字符串添加jbuilder属性

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?

我正在使用rails和jBuilder在我的应用程序中提供JSON。我试图迭代各种颜色,仅当它们的值不是nil时才将它们添加到结果JSON中。这是我正在使用的,这是有效的,但我想学习如何公关

工作代码

非工作代码

“json[color]”部分是罪魁祸首,因为如果我只使用json.blah,它就可以工作。有什么建议吗?

这可能会有帮助

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