我有一个名为的模型Location,它在创建时使用 Geocoder 从坐标中检索地址。然后我有一个 Android 应用程序,它向控制器询问index我的方法中特定点周围的位置列表locations_controller:
def index
    @locations = Location.near([params[:latitude], params[:longitude]], params[:search_radius], :order => :distance)
end
结果用 Rabl 格式化为 json 并发送到应用程序:
child :data do
  child @location do
    attributes :id, :name, :address, :city, :state, :zipcode, :country_name, :latitude, :longitude, :distance
  end
end
到目前为止它运行良好,并且:distance是自动计算的。
但是现在我让用户可以Location在应用程序中创建一个,所以我这样设计了create这个方法:
def create
  @location = Location.new(params[:location])
  if @location.save
    @location
  else
    render :status => :unprocessable_entity,
           :json => { :success => false,
                      :info => @location.errors,
                      :data => {} }
  end
end
创建效果很好,我可以将包含基本信息的 rabl 文件发送给用户,但我的问题是:distance没有计算出来。
我想使用与该index方法相同的 Rabl 模板并添加类似这样的内容,但它不起作用:
node(:distance) { |location| location.distance_to(params[:latitude], params[:longitude]) }
我可以使用 Rabl 文件中的参数来计算它吗?
还是我必须在控制器中进行?我需要在模型中添加属性吗?
更新
这是我的Location模型:
class Location < ActiveRecord::Base
    attr_accessible :address, :city, :state, :zipcode, :country_name, :latitude, :longitude, :name
    reverse_geocoded_by :latitude, :longitude do |obj,results|
      if geo = results.first
          obj.address = geo.street_address
          obj.city = geo.city
          obj.state = geo.state_code
          obj.zipcode = geo.postal_code
          obj.country_name = geo.country
      end
   end
   after_validation :reverse_geocode
end