Question

I've got an app that uses rails geocoder to find locations of registered users by their provided zip code. This works well for registered users, but I also want to extend some functionality to guest users. I'm using devise's solution for guest users as shown in this link: https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user

Here's my user model:

class User < ActiveRecord::Base

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

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

end

Here's my create_guest_user method:

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

I want to geocode a guest_user's location by their IP. Is there a way I can call a geocode method in my create_guest_user method and then pass the values of lat and long when the guest user is created? Any help is much appreciated, thanks in advance!

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top