如何进行模型并解析数组user_location,以便我可以像手动示例一样解析to_lng_lat?
class User
include Mongoid::Document
include Mongoid::Geospatial
devise :database_authenticatable, :registerable
field :email, :type => String, :default => ""
field :encrypted_password, :type => String, :default => ""
field :user_location, :type => Point, :spatial => true
before_save :set_user_location
protected
def set_user_location
# manual save works
# self.user_location = [52.38, 18.91].to_lng_lat
end
end
重写了devise user_controller:
def update
puts JSON.parse params[:user][:user_location]
# gives raw:
# 52.38
# 18.91
super
end
是否可以在不在模型中覆盖设计控制器的情况下执行此操作?
查看:
= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f|
= f.email_field :email
= f.password_field :current_password
= f.hidden_field :user_location
= f.submit "Update"
JavaScript的:
var user_location = JSON.stringify([52.38, 18.91]);
$("#user_user_location").val(user_location);
答案 0 :(得分:1)
您可以在User
声明后覆盖setter,而不是在field :user_location
模型中创建单独的setter。由于通过将属性传递给模型来隐式使用这些setter,我相信这将允许您避免对控制器进行任何特定更改以支持JSON解析位置。
class User < ActiveRecord::Base
# rest of class omitted, remove 'set_user_location' code
def user_location=(location)
case location
when String
super(JSON.parse(location))
else
super
end
end
end
这比我更好,而不是凌驾设计控制器;我不必考虑在以这种方式设置数据的每个上下文或控制器中进行此转换。