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 に答える