0
我有一个位置属性的模型,它是一个包含两个元素的数组;纬度和经度。我定义为位置访问器这样访问器和update_attributes
class Address
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Spacial::Document
field :location, :type => Array, spacial: {lat: :latitude, lng: :longitude, return_array: true }
#accessors for location
def latitude
location[0]
end
def latitude=(lat)
location[0] = latitude
end
def longitude
location[1]
end
def longitude=(lng)
location[1] = lng
end
attr_accessible :location, :latitude, :longitude
end
这里是控制器代码
def create
@address = Address.new(params[:address])
if @address.save
redirect_to :action => 'index'
else
render :action => 'new'
end
end
def update
@address = Address.find(params[:id])
if @address.update_attributes(params[:address])
redirect_to :action => 'index'
else
render :action => 'edit'
end
end
和在视图级别
<%= f.hidden_field :latitude%>
<%= f.hidden_field :longitude%>
这些隐藏字段经由JS操纵,并且没问题。只见它查看开发人员工具
下面是参数控制器接收
"address"=>{"latitude"=>"-38.0112418", "longitude"=>"-57.53713060000001", "city_id"=>"504caba825ef893715000001", "street"=>"alte. brown", "number"=>"1234", "phone"=>"223 4568965"}, "commit"=>"Guardar", "id"=>"504cacc825ef893715000006"}
注意改变经纬度参数,那OK,但这种变化是不是保存到MongoDB的
所以,纬度和经度的值不会被保存。有没有我的代码丢失的任何指示?
在此先感谢。
---编辑---
这里的工作访问器
def latitude
location[0]
end
def latitude=(lat)
self.location = [lat,self.location[1]]
end
def longitude
location[1]
end
def longitude=(lng)
self.location = [self.location[0], lng]
end
我不知道在这种情况下,这是真的 - '位置[0] = foo'不在那个位置'= foo'是 –
@FrederickCheung的方式含糊:你是对的,只是试过。现在很明显,否则会引发异常。尽管如此,在这种情况下使用'self'是个好习惯,我认为这个问题是由于不正确的设置方法 – apneadiving
谢谢。我看到了错误。但在拼写错误旁边,我用你的帮助和self.location = [lat,self.location [1]]解决了这个问题。我不明白为什么我需要创建一个新的数组。谢谢! –