2017-04-02 66 views
0

我試圖遍歷數據的每個屬性,並且使用下面的模型方法中的值。如果我將值推入到check []數組中,則該函數可以工作,但如果我嘗試使用datum.attr_name = datum.attr_value.downcase,則不會採用降級。循環遍歷每個屬性並降低

我該如何實際降低每個屬性值並讓這個向下保存?

check = [] #used to troubleshoot 
datum.attributes.each do |attr_name, attr_value| 
    begin 
    check.push(attr_name) #just used to troubleshoot 
    check.push(attr_value.downcase) #just used to troubleshoot 

    datum.attr_name = datum.attr_value.downcase #need help here 

    rescue 
    end 
end 
datum.save 
return check 

紅利:我目前正在使用數組進行故障排除,並通過錯誤消息將該數組打印出來。排除這種模型代碼的更好方法是什麼?

回答

1

您可以這樣做,也可以通過檢查屬性是否可以降級來擺脫begin...rescue

datum.attributes.each do |attr_name, attr_value| 
    datum[attr_name] = attr_value.downcase if attr_value.respond_to?(:downcase) 
end 
datum.save 
+1

這讓我接觸到解決方案。 'datum [attr_name] = attr_value.downcase'工作。我們應該從解決方案中刪除'datum.',我會接受嗎? – HoosierCoder

+0

當然是,編輯它。 – Iceman

+1

respond_to電話..很好 – HoosierCoder