ruby - Using Model.create when the parent class is not already saved -


i'm trying create translate keyword create class member working simple string different values, depending of locale set.

here code :

module translate   def translate(*attr_name)     _field_name = attr_name[0]     has_many :translations     define_method(_field_name)       self.translations.where(key: _field_name, locale: i18n.locale).first     end     define_method("#{_field_name}=") |params|       self.translations.create!(key: _field_name, locale: i18n.locale, value: params.to_s)     end   end end  class translation   include mongoid::document   field :key, type: string   field :value, type: string, default: ''   field :locale, type: string    belongs_to :productend end  class product   include mongoid::document   extend translate   translate :description end 

i'm getting error :

mongoid::errors::unsaveddocument:  problem:   attempted save translation before parent product. summary:   cannot call create or create! through relation (translation) who's parent (product) not saved. case database out of sync since child potentially reference nonexistant parent. resolution:   make sure use create or create! when parent document product persisted. /library/ruby/gems/2.0.0/gems/mongoid-3.1.7/lib/mongoid/relations/proxy.rb:171:in `raise_unsaved' 

your problem spelled out in error message need create product before can try , create associated records.

meaning can't work:

product = product.new product.translations.create! 

this can:

product = product.create product.translations.create! 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -