在尚未保存父级 class 时使用 Model.create

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

我正在尝试创建一个 translate 关键字来创建一个 class 成员,它像一个简单的字符串一样工作,但具有不同的值,具体取决于区域设置。

这是我的代码:

module Translate
  def translate(*attr_name)
    _field_name = attr_name[0]
    has_many :translations
    define_method(_field_name) do
      self.translations.where(key: _field_name, locale: I18n.locale).first
    end
    define_method("#{_field_name}=") do |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

我遇到了这个错误:

Mongoid::Errors::UnsavedDocument: 
Problem:
  Attempted to save Translation before the parent Product.
Summary:
  You cannot call create or create! through the relation (Translation) who's parent (Product) is not already saved. This would case the database to be out of sync since the child could potentially reference a nonexistant parent.
Resolution:
  Make sure to only use create or create! when the parent document Product is persisted.
from /Library/Ruby/Gems/2.0.0/gems/mongoid-3.1.7/lib/mongoid/relations/proxy.rb:171:in `raise_unsaved'

您的问题已在错误消息中详细说明,但您只需创建一个 Product 即可尝试创建关联记录。

意思是这行不通:

product = Product.new
product.translations.create!

这可以:

product = Product.create
product.translations.create!