我似乎无法在这里或谷歌找到答案,任何帮助都会很棒。 建筑物保存正确,但嵌入式文档PriorityArea不会更新... 我希望最终能够为新的优先领域创建一个新形式,但需要先更新。
class Building
include Mongoid::Document
embeds_many :priority_areas
accepts_nested_attributes_for :priority_areas, :allow_destroy => true, :autosave => true
end
class PriorityArea
include Mongoid::Document
embedded_in :building, :inverse_of => :priority_areas
end
#view
= form_for [@customer, @building] do |f|
...
...
= f.fields_for :priority_areas do |pa|
= f.name
...
...
#controller
@building.update_attributes(params[:building])
它正确地从数据库中提供了正确的数据,但在构建#update时未能出错。非常感谢任何帮助。
更新 在建筑物#update im put params [:building] [:priority_areas_attributes] .to_yaml
哪些是
--- !map:ActiveSupport::HashWithIndifferentAccess
"0": !map:ActiveSupport::HashWithIndifferentAccess
name: area 51
location: near front door
notes: ""
priority: "1"
id: ""
"1": !map:ActiveSupport::HashWithIndifferentAccess
name: area 52
location: near rear door
notes: ""
priority: "2"
id: ""
我猜测问题是空id:“”
答案 0 :(得分:1)
问题是null id 它需要一个ObjectId才能正常工作。我这个愚蠢的错误。
答案 1 :(得分:0)
我遇到了确切的问题。 simple_form
自动将id参数传递给我的控制器,但它是空白的。
为什么嵌入式文档的ID为空?我猜是因为我通过mongoimport导入了父文档。如果我通过Web表单手动生成父文档,则嵌入的文档具有预期的ID。
以下是我的解决方法:
class Foo
include Mongoid::Document
embeds_many :bars
accepts_nested_attributes_for :bars
####
# simple_form_for / embedded document workaround
#
# Because simple_form wants to provide the ID for an existing object,
# it will output a blank ID because imported embedded documents
# have an ID of nil.
#
# Intercept it to avoid
# Mongoid::Errors::InvalidFind in FoosController#update
def bars_attributes=(attribs)
attribs.each do |key, value|
index = key.to_i
fixed_attrib = value.delete_if { |k,v| k=="id" and v=="" }
self.bars[index].update_attributes(fixed_attrib)
end
end
end
class Bar
include Mongoid::Document
embedded_in :foo
end