ruby on rails - undefined method `name' for nil:NilClass for custom slug -
i have restaurant model use geocoder gather city, state, , neighborhood on before_validation callback.
class restaurant < activerecord::base # attrs: :name, :address, :city_id, :neighborhood_id ... before_validation :geocode geocoded_by :address |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 city model i've put custom slug uses city's name , state's name 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 create new restaurant i'm error:
undefined method `name' nil:nilclass def state_slug "#{name} #{state.name}" end understandably because there isn't city or state has yet persisted database. i'm wondering how can configure callback work?
write method in city model. generate slug when state id got changed.
def should_generate_new_friendly_id? new_record? || state_id_changed? end and make little change following method.
def state_slug "#{name} #{state.name}" if state.present? end
Comments
Post a Comment