1
我試圖創建一個translate
關鍵字,創造了一流的人工作是一個簡單的字符串,但使用不同的值,這取決於語言環境設置的。使用Model.create當父類尚未保存
這裏是我的代碼:
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'
它在說產品尚未保存,在那裏創建? – Anthony
我與'P = Product.new'控制檯來測試我的代碼創建它。 – Morniak
權,嘗試'P = Product.create' – Anthony