2015-11-05 69 views
1

我想在Ruby中创建一个JSON对象与属性添加有条件红宝石构建JSON有条件

step_json = { 
    "id" => step.id, 
    "name" => step.name, 
    "position" => step.position, 
    "ancestry" => step.ancestry, 
    "image_path" => (step.first_image.image_path_url || step.first_image.s3_filepath) if step.first_image.present?, 
    "label" => step.label if step.label.present?, 
    "label_color" => step.last_color if step.label.present? 
    } 

我收到的错误给我的条件语句。有没有办法做到这一点,而不是做整个step_json对象周围的if/else语句?

回答

0

创建静态条目后,您可以有条件地向对象添加单个条目。

step_json = { 
    "id" => step.id, 
    "name" => step.name, 
    "position" => step.position, 
    "ancestry" => step.ancestry 
} 
step_json['image_path'] = (step.first_image.image_path_url || step.first_image.s3_filepath) if step.first_image.present? 
step_json['label'] = step.label if step.label.present? 
step_json['label_color'] = step.last_color if step.label.present? 
+0

谢谢 - 这工作! – scientiffic