0

我有一个应用程序,它使用 rails geocoder 通过提供的邮政编码查找注册用户的位置。这对注册用户很有效,但我也想将一些功能扩展到来宾用户。我正在为来宾用户使用设计的解决方案,如以下链接所示:https ://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user

这是我的用户模型:

class User < ActiveRecord::Base

devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

validates :zip, presence: true
geocoded_by :zip
after_validation :geocode

end

这是我的create_guest_user方法:

def create_guest_user
    u = User.create(:name => "guest", :email => "guest_#{Time.now.to_i}#{rand(99)}@example.com")
    u.save!(:validate => false)
    session[:guest_user_id] = u.id
    u
end

我想通过他们的 IP 对 guest_user 的位置进行地理编码。有没有一种方法可以在我的方法中调用地理编码方法create_guest_user,然后在创建来宾用户时传递 lat 和 long 的值?非常感谢任何帮助,在此先感谢!

4

1 回答 1

1

Have you tried passing a condition to geocoded_by? I browsed through the docs for an example and couldn't find one, but it's worth a try at least.

class User
  geocoded_by :ip_address, :if => :name == "guest"
end

If that doesn't work, you can define a new method to geocode by (like in the example given for address here):

class User
  validates_presence_of :zip, :if => non_guest #(or however you define a real user)
  geocoded_by :zip_or_ip
  after_validation :geocode

  def zip_or_ip
    if name == 'guest'
      :ip_address
    else
      :zip
    end
  end
end

and then get rid of the :validate => false in your controller (or keep it if you need to for other things).

于 2013-11-21T04:55:13.007 回答