Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 是否可以使用mongoid;嵌套属性“;从属于一对多关系的一方?_Ruby_Mongodb_Mongoid - Fatal编程技术网

Ruby 是否可以使用mongoid;嵌套属性“;从属于一对多关系的一方?

Ruby 是否可以使用mongoid;嵌套属性“;从属于一对多关系的一方?,ruby,mongodb,mongoid,Ruby,Mongodb,Mongoid,是否可以从属于一对一关系的一侧使用mongoid“” 例如: class Bar1 include Mongoid::Document belongs_to :bar2 accepts_nested_attributes_for :bar2 end 当我试图访问嵌套属性时,我得到以下异常:NoMethodError:undefined方法'bar2_attributes' 我的主要目标是使用“嵌套属性”功能缓存引用的文档属性 我做错了什么?当您应该使用数组访问方法时,您可能正试

是否可以从属于一对一关系的一侧使用mongoid“”

例如:

class Bar1
  include Mongoid::Document

  belongs_to :bar2

  accepts_nested_attributes_for :bar2
end
当我试图访问嵌套属性时,我得到以下异常:NoMethodError:undefined方法'bar2_attributes'

我的主要目标是使用“嵌套属性”功能缓存引用的文档属性


我做错了什么?

当您应该使用数组访问方法时,您可能正试图以类似
Class.attr的方法访问它:
Class['attr']
。我的猜测是,即使它不是一个动态字段,规则仍然适用,因为它是嵌套的,可能还不存在

来自mongoid文档 默认情况下,Mongoid支持动态字段——也就是说,即使没有为属性定义字段,它也允许在文档上设置和持久化属性。然而,在处理动态属性时,有一点“抓到了”,因为Mongoid对方法的使用并不完全宽容,因为它丢失并破坏了Document类的公共接口。 处理动态属性时,以下规则适用: 如果该属性存在于文档中,Mongoid将为您提供标准的getter和setter方法。例如,考虑一个在文档中设置了“性别”属性的人:

将此人的性别设置为男性。 获取此人的性别。 如果该属性在文档中不存在,Mongoid将不会向您提供getter和setter,并将强制执行正常的method\u缺失行为。在这种情况下,您必须使用其他提供的访问器方法:([]和[]=)或(read_属性和write_属性)

如果未设置值,则引发NoMethodError。 安全地检索动态字段。 安全地写入动态字段。
通过将Mongoid配置选项allow\u Dynamic\u fields设置为false,可以完全关闭动态属性。

我再次阅读了文档,现在了解到“netsted attributes”用于保存数据。并且不能用于缓存引用的文档。

您是说“嵌套属性”功能吗?我想你还没明白我的意思。不,我明白了。我认为这是相关的。尝试通过[]方法访问它们。我已经再次阅读了文档,现在知道“netsted属性”用于保存数据。并且不能用于缓存引用的文档。
person[:gender] = "Male"
person.gender = "Male"
person.gender
person.gender
person.gender = "Male"
person[:gender]
person.read_attribute(:gender)
person[:gender] = "Male"
person.write_attribute(:gender, "Male")