0

如何在模型中进行并解析到数组 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

覆盖设计 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);
4

1 回答 1

1

无需在模型中创建单独的设置器User,您可以覆盖提供field :user_location声明的设置器。由于这些设置器是通过将属性传递给模型来隐式使用的,我相信这将允许您避免对控制器进行任何特定更改以支持 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

这对我来说比重写设计控制器更可取;我不必考虑在以这种方式设置数据的每个上下文或控制器中进行这种转换。

于 2012-10-12T10:00:41.687 回答