سؤال

I have a model named Menu which has product_types that belong to it.

Upon creation of the menu I want to set some default product_types:

I have this constant:

DEFAULTS = [ 
  { name_en: 'White bread', name_nl: 'Wit brood', name_fr: 'Pain blanc'},
  { name_en: 'Brown bread', name_nl: 'Bruin brood', name_fr: 'Pain brun' }
]

And this should create the translations but I get an error at the moment saying:

"You cannot call create unless the parent is saved"

def create_defaults
  ProductType::DEFAULTS.each do |pt|
    t = product_types.create
    t.translations.create(locale: 'en', name: pt[:name_en])
    t.translations.create(locale: 'nl', name: pt[:name_nl])
    t.translations.create(locale: 'fr', name: pt[:name_fr])
  end

The menu can be in 3 languages (selectable by the user) and the user also has a default language. This default language can be dutch, english or french. So it's possible to have an dutch user with languages of the menu in dutch and french.

The code I also tried before (that didn't give an error msg) was:

 def create_defaults
   ProductType::DEFAULTS.each do |pt|
     t = product_types.create(name: pt[:name_en])
     t.translations.create(locale: 'nl', name: pt[:name_nl])
     t.translations.create(locale: 'fr', name: pt[:name_fr])
   end
 end

The problem with this procedure is: suppose the user his default language is set to dutch and the language of the menu is set to dutch as well (no other languages). Then the default created types appear in english...

هل كانت مفيدة؟

المحلول

This does the trick:

def create_defaults
  ProductType::DEFAULTS.each do |pt|
    t = product_types.create
    t.translations.build(locale: 'en', name: pt[:name_en])
    t.translations.build(locale: 'nl', name: pt[:name_nl])
    t.translations.build(locale: 'fr', name: pt[:name_fr])
    t.save
  end
end

When saving the parent all the child objects are saved as well.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top