2015-11-05 70 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