レコードで update_attributes を使用しようとしていますが、失敗し、その理由がわかりません。その方法を何度も使用したため、明らかな何かが欠けているに違いありません。
Globalize3
名前変数を使用するモデルのデータをシードしようとしています。
class City < ActiveRecord::Base
attr_accessible :name
translates :name
end
City には という名前の列がないことに注意してくださいname
。
コンソールでは、 のようなことをしても問題ありませんcity.update_attributes(name: "new name")
が、次のコード ( 内) はfirstseeds.rb
で失敗し続けます:Undefined method
for 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