修改活动记录响应

时间:2013-02-27 13:27:17

标签: ruby-on-rails-3

这似乎是一个基本问题,但我无法绕过它。我从数据库中获取了一些数据并将其作为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>

1 个答案:

答案 0 :(得分: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>

您的控制器所要做的就是从DB获取位置:

@locations = Location.all.order(:created_at)
相关问题