ruby-on-railsglobalize3

How can I create_or_update in seeds.rb for translations?


I now have the following in my seeds.rb

os = OrderStatus.find(1)
os.translations.create(:status => "In aanmaak", :locale => "nl")
os.translations.create(:status => "Creating", :locale => "en")

However this creates doubles. So I tried to do a create_or_update instead of create but that doesn't seem to be supported. I am using globalize3


Solution

  • Based on your comment you could do the following:

    os = OrderStatus.find(1)
    os.translations.where(locale: "nl").first_or_create.update_attributes(status: "In aanmaak")
    os.translations.where(locale: "en").first_or_create.update_attributes(status: "Creating")
    

    I'm not sure if there's a nicer way of writing this, but you could create your own method:

    class Translation < ActiveRecord::Base
      def first_or_update(locale, status)
        where(locale: locale).first_or_create.update_attributes(status: status)
      end
    end
    
    os.translations.first_or_update("en", "Creating")