我试图创建一个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'
您的问题在错误消息中详细说明了,但是您只需要在尝试创建相关记录之前创建一个Product
。
意味着这个不能工作:
product = Product.new
product.translations.create!
这可以:
product = Product.create
product.translations.create!