0

レコードで update_attributes を使用しようとしていますが、失敗し、その理由がわかりません。その方法を何度も使用したため、明らかな何かが欠けているに違いありません。

Globalize3名前変数を使用するモデルのデータをシードしようとしています。

class City < ActiveRecord::Base
  attr_accessible :name

  translates :name
end

City には という名前の列がないことに注意してくださいname

コンソールでは、 のようなことをしても問題ありませんcity.update_attributes(name: "new name")が、次のコード ( 内) はfirstseeds.rbで失敗し続けます:Undefined methodfor 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は次のように定義されています。

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
4

1 に答える 1

1

私は最終的にトレースを使用してそれを理解しました。

with_locale私のカスタム メソッドも globalize3 によって定義されており、あらゆる種類の問題を引き起こしていることが判明しました。

のおかげで@cthulhu、それを知りI18n.with_locale、代わりにそれを使用しました。

于 2012-09-25T15:06:07.157 に答える