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]]解決了這個問題。我不明白爲什麼我需要創建一個新的數組。謝謝! –