2010-05-28 74 views
0

我正在從一個從一個JSON提要導入到一個名爲Person的ActiveRecord的耙子任務。設置許多鍵/值對

人有很多屬性,而不是寫代碼行來設置每個屬性我試着使用不同的方法。

我得到的最接近的是如下所示。這在輸出到屏幕時效果很好,但是當我檢查實際上在ActiveRecord上設置的值時,它始終爲零。 因此,它看起來像我不能使用.to_sym解決我的問題?

有什麼建議嗎?

我還要提到的是,我剛開始使用Ruby,已經做了不少的Objective-C的,現在需要擁抱Interwebs :)

 http = Net::HTTP.new(url.host, url.port) 
http.read_timeout = 30 
json = http.get(url.to_s).body 
parsed = JSON.parse(json) 
if parsed.has_key? 'code' 
    updatePerson = Person.find_or_initialize_by_code(parsed['code']) 
    puts updatePerson.code 
    parsed.each do |key, value| 
    puts "#{key} is #{value}" 
     symkey = key.to_sym 
     updatePerson[:symkey] = value.to_s 
     updatePerson.save 
     puts "#{key}....." # shows the current key 
     puts updatePerson[:symkey] # shows the correct value 
     puts updatePerson.first_name # a sample key, it's returning nil 

end 

回答

0

您可以使用write_attribute

parsed.each do |key, value| 
    updatePerson.write_attribute(key, value) 
end 
updatePerson.save 
+0

感謝您的建議,這是讓我使用以下代碼: parsed。每個|鍵,值| if value.class!= Array updatePerson.write_attribute(key,value) end end updatePerson.save – iOSDevil 2010-05-28 12:53:58

1

你可能尋找update_attributes()

if parsed.has_key?('code') 
    code = parsed.delete('code') 
    person = Person.find_or_initialize_by_code(code) 
    if person.update_attributes(parsed) 
    puts "#{person.first_name} successfully saved" 
    else 
    puts "Failed to save #{person.first_name}" 
    end 
end 
+0

感謝PAR屬性, 那看起來很方便,但它並不完全是銀色的子彈,因爲解析的JSON也包含一些數組。我猜我需要過濾掉(也許如果class = Array),因爲我得到一個錯誤: rake中止! 未初始化的常量Person ::結果 – iOSDevil 2010-05-28 08:40:19

+0

您應該確保傳遞給'update_attributes'的散列僅包含與模型屬性對應的鍵/值對。這些可以通過將散列中的鍵與'Person#attribute_names'(http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001868)進行比較來過濾掉。但是,您收到的錯誤消息似乎表明存在另一個問題 - 您嘗試在代碼中引用'Person :: Result'而未定義它。您可以通過對代碼所做的任何更改來更新問題嗎? – 2010-05-28 12:16:17

1

您的代碼不能將任何屬性,因爲你總是分配給名爲「symkey」的單一屬性:

symkey = key.to_sym 
updatePerson[:symkey] = value.to_s # assigns to attribute "symkey", not to the attribute with the name stored in variable symkey 

如果你想使鑰匙插入的符號(這可能甚至不是必要的),然後使用作爲訪問的updatePerson屬性的索引,你可以寫:

updatePerson[key.to_sym] = value.to_s 
updatePerson.save 

但這 - 或多或少 - 相同

updatePerson.updateAttribute(key.to_sym, value.to_s) # update and save 

除了沒有驗證的三呃,小心使用。

性能方面,在每次分配後保存個人可能不是一個好主意,所以也許您希望推遲撥打.save(),直到分配完所有屬性。

儘管如此,updateAttributes(...)是你可能想尋找到的東西 - 如果你做什麼,不要忘記告知自己在attr_protectedattr_accessible,因爲他們保護「批量分配」