2013-02-27 25 views
0

這似乎是這樣一個基本問題,我不能理解它。我從數據庫中獲取一些數據並將其作爲JSON提供。在我將它作爲JSON服務之前,我想爲數組中的每個散列值添加一個值。修改一個有效的記錄回覆

@locations.each do |location| 
    if location[:image].present? 
    location[:convient_new_url_value] = 'http://site.com/#{location.image}.jpg' 
    end 
end 

但是,我似乎無法將值添加到散列。我採取了錯誤的做法嗎?

**對不起 - 更多信息**

@locations = Location.find(:all, :order => "created_at") 

@locations.each do |location| 

    if location[:image].present? 
    location[:convient_new_url_value] = 'http://site.com/#{location.image}.jpg' 
    end 
end 

respond_to do |format| 
    format.html 
end 

的JSON是在HTML模板製作:

<script> 
    var location_data = <%= raw @locations.to_json() %> 
</script> 
+0

如果我們能夠看到「位置」實際是什麼,以及它如何提供給視圖,會更容易。 – 2013-02-27 13:40:32

+0

修正了爲了使它更清晰... – Jim 2013-02-27 13:47:24

+0

'locations'不是一個散列,它是一個活動的記錄關係。該集合中的每個對象都是AR,而不是通用散列; AFAIK在to_json中沒有任何東西可以做除檢查其實際屬性之外的任何事情,而忽略專門的東西進入它。 IIRC'[] ='解析爲'write_attribute',如果該屬性實際上不存在於模型本身中,我不認爲它會被序列化。 – 2013-02-27 13:51:03

回答

0

最簡單的方法很可能會在你的模型convient_new_url_value創建方法並將其傳遞給to_json

class Location < ActiveRecord::Base 
    ... 
    def convient_new_url_value 
    "http://site.com/#{self.image}.jpg" if self.image.present? 
    end 
end 

<script> 
    var location_data = <%= raw @locations.to_json(:methods => :convient_new_url_value) %> 
</script> 

所有控制器必須做的是ge t來自DB的位置:

@locations = Location.all.order(:created_at)