setting mongoid hash field values

做~自己de王妃 提交于 2019-12-05 01:07:06
Jagjot Singh

The thing with Hash field is, it can be dynamic as much as you want. Therefore to prevent polluting your DB schema with unintended fields caused by bugs in your code this functionality is disabled by default.

No you are not stuck using 2-step updates for your hashes at all!

[],[]= are the shortcuts for read_attribute() and write_attribute() and should be used if you don't include Mongoid::Attributes::Dynamic. If you try to use $set without enabling dynamic attributes you will get a no-method error because it does not see your dynamic attributes as defined attributes.

If you'll read the source of Mongoid::Attributes::Dynamic then you'd find that this is required to add the dynamic attributes functionality.

To update the values by including Mongoid::Attributes::Dynamic you need to follow these steps:

thing = Thing.first
thing.set("info.endDate" => Time.now)
thing.reload # This will update the current variable 

Otherwise if you need you can easily skip this and do the value update by 2-step method

I hope this sheds some light over your query.

Source:

Rails mongoid dynamic fields - no method error

Dynamic attributes with Rails and Mongoid

I think you pass parameter in wrong way. Replace arrow symbol with comma

You can change to this and it will work

thing.set("info.endDate", Time.now) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!