ruby-on-rails/ model/ rails-geocoder

I've currently got my code working so that the Geocoder takes the user's IP address and saves the physical (along with a hard-coded IP address for development):

class User < ActiveRecord::Base
    geocoded_by :ip_address
    after_validation :geocode

    reverse_geocoded_by :latitude, :longitude
    after_validation :reverse_geocode

    def self.remote_ip
        if $request.remote_ip == '127.0.0.1'
          '111.11.333.666'
        else
          $request.remote_ip
        end
    end  

  user.ip_address = remote_ip
  user.location = user.address

Now I'm trying to get the city from the address. Looking at the docs, it provides this:

reverse_geocoded_by :latitude, :longitude do |obj,results|
    if geo = results.first
      obj.city    = geo.city
      obj.zipcode = geo.postal_code
      obj.country = geo.country_code
    end
 end
after_validation :reverse_geocode

This keeps giving me an "undefined method `city=' for User:" error.

Looking at this question asked previously on stackoverflow, Rails Geocoder "undefined method error" and Can Ruby Geocoder return just the street name on reverse_geocode calls? , it says that I have to pass the model name instead of "obj" in the block above. How do I do that? I tried user,results but that didn't work.

As Cody pointed out, I needed to add the city and country fields to my User model via migrations first.

 rails g migration AddCityToUsers city:string
 rails g migration AddCountryToUsers country:string

Final code:

reverse_geocoded_by :latitude, :longitude do |obj,results|
if geo = results.first
  obj.city    = geo.city
  obj.country    = geo.country
end
end
after_validation :reverse_geocode

user.location = user.city + ", " + user.country

Why not just:

reverse_geocoded_by :latitude, :longitude do |obj,results|
  if geo = results.first
    obj.city = geo.city
    obj.country = geo.country
    # make a combined field with both city/country
    obj.location = geo.city + ", " + geo.country
  end
end
after_validation :reverse_geocode

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question Rails geocoder gem find city Using the geocoder gem for rails, how do i get the visitor's city? Rails Active Record .pluck not working with polymorphic model using geocoder Ordering posts by distance to city using geocoder Using Geocoder Rails with Sidekiq Rails 3 - How to represent User model which belongs_to a City? Ruby on Rails - Restrict geocoder response to city and get the ID How to get full list of Rails' Geocoder city names? Rails 4: Saving User selections with a Nested Model Form Saving attributes fields in devise User model in Rails 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM