I have a Restaurant
model that use Geocoder to gather the city, state, and neighborhood on a before_validation
callback.
class Restaurant < ActiveRecord::Base
# attrs: :name, :address, :city_id, :neighborhood_id
...
before_validation :geocode
geocoded_by :address do |obj,results|
if geo = results.first
obj.city = City.where(name: geo.city).first_or_create
obj.city.update_attributes(state: State.where(name: geo.state).first_or_create)
obj.neighborhood = Neighborhood.where(name: geo.neighborhood).first_or_create
obj.neighborhood.update_attributes(city: City.where(name: geo.city).first_or_create)
obj.longitude = geo.longitude
obj.latitude = geo.latitude
end
end
end
In my City
model I've put together a custom slug which uses the city's name and the state's name that it belongs to.
class City < ActiveRecord::Base
# attrs :name, state_id
belongs_to :state
friendly_id :state_slug, use: :slugged
def state_slug
"#{name} #{state.name}"
end
end
Whenever I create a new restaurant I'm the error:
undefined method `name' for nil:NilClass
def state_slug
"#{name} #{state.name}"
end
Understandably because there isn't a city or state that has yet to be persisted to the database. I'm wondering how can I configure my callback to get this to work?