Question

I'm trying to use update_attributes on a record, but it fails and I can't figure out why, I must be missing something obvious as I've used that method plenty of times.

I'm trying to seed data for a model that uses Globalize3 for its name variable.

class City < ActiveRecord::Base
  attr_accessible :name

  translates :name
end

Note that City has no column named name.

In the console I have no issue doing something like city.update_attributes(name: "new name"), but the following code (in seeds.rb) keeps failing with Undefined methodfirstfor nil:NilClass:

localized_cities_attributes = [
  { en: { name: "New York City" }, fr: { name: "New York" } },
  { en: { name: "Montreal" }, fr: { name: "Montréal" } }
]
localized_cities_attributes.each do |city_localized_attributes|
  city = nil

  city_localized_attributes.each do |locale, attributes|
    with_locale(locale) do
      if city
        city.update_attributes(name: attributes[:name])
      elsif (city = City.find_by_name(attributes[:name])).nil?
        city = City.create(attributes)
      end
    end
  end
end

with_locale is defined as such:

def with_locale(new_locale, &block)
  return if block.nil?

  locale_to_restore = I18n.locale
  I18n.locale = new_locale
  block.call
  I18n.locale = locale_to_restore
  nil
end
Was it helpful?

Solution

I finally figured it out using the trace.

It turns out my custom method with_locale is also defined by globalize3 and caused all sorts of issues.

Thanks to @cthulhu, I found out about I18n.with_locale and used that instead.

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