宝石版 我正在使用Rails 3.2.18和Mongoid 3.1.6。
问题 我需要为本地化字段中的任何语言环境设置一个值,而不仅仅是当前位于I18n.locale中的语言环境。我使用title_translations ['en'] ='some title'设置它,但是当这样做时,mongoid不会检测到更改(不是脏),因此没有保存任何内容。
模特 我有一个具有本地化字段的mongoid模型,如下所示:
class ApiMethod
include Mongoid::Document
field :title, type: String, localize: true
attr_accessible :title, :title_translations
end
控制台示例 下面是两个方式设置标题的示例,一个是title ='xxx',另一个是title_translations ['en'] ='xxx',以及测试对象是否已更改的结果。
2.1.2 :083 > a = ApiMethod.first
=> #<ApiMethod _id: 5541cb17fb6fc67028000006, title: {"en"=>"Dataset Catalog"}>
2.1.2 :084 > a.title
=> "Dataset Catalog"
2.1.2 :085 > a.title_translations
=> {"en"=>"Dataset Catalog"}
2.1.2 :086 > a.title = 'new title'
=> "new title"
2.1.2 :087 > a.changed?
=> true ## YEA! - THIS IS CORRECT
2.1.2 :088 > a.changed
=> ["title"]
2.1.2 :089 > a.reload
=> #<ApiMethod _id: 5541cb17fb6fc67028000006, title: {"en"=>"Dataset Catalog"}>
2.1.2 :090 > a.title_translations['en'] = 'this is a new title'
=> "this is a new title"
2.1.2 :091 > a.title
=> "this is a new title"
2.1.2 :092 > a.title_translations
=> {"en"=>"this is a new title"}
2.1.2 :093 > a.changed?
=> false ## BOO! - THIS IS NOT CORRECT
请帮忙! 我做错了什么或遗失了什么?是否无法为不是当前I18n.locale值的语言环境设置本地化字段值?
感谢您的帮助!
更新 我只是尝试了别的东西,这很有效。我尝试设置整个title_translations对象,而不是设置特定区域设置的title_translations:
2.1.2 :114 > a = ApiMethod.only(:title).first
=> #<ApiMethod _id: 5541cb17fb6fc67028000006, title: {"en"=>"Dataset Catalog"}>
2.1.2 :115 > x = a.title_translations.dup
=> {"en"=>"Dataset Catalog"}
2.1.2 :116 > x['en'] = 'this is a new title'
=> "this is a new title"
2.1.2 :117 > x
=> {"en"=>"this is a new title"}
2.1.2 :118 > a.title_translations = x
=> {"en"=>"this is a new title"}
2.1.2 :119 > a.title_translations
=> {"en"=>"this is a new title"}
2.1.2 :120 > a.changed?
=> true
2.1.2 :121 > a.title_change
=> [{"en"=>"Dataset Catalog"}, {"en"=>"this is a new title"}]
因此,如果我替换title_translations的整个值而不仅仅是特定的语言环境,则会检测到更改。虽然这很好用,但它并不理想。想法?