当父类尚未保存时使用Model.create

时间:2015-09-21 12:21:51

标签: ruby mongodb sinatra mongoid

我尝试创建一个translate关键字,创建一个类成员,就像一个简单的字符串,但具有不同的值,具体取决于区域设置。

这是我的代码:

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'

1 个答案:

答案 0 :(得分:1)

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

这意味着无法工作:

product = Product.new
product.translations.create!

这可以:

product = Product.create
product.translations.create!