MongoDB [已解决] mongoid 的短板?无法实现 accepts_nested_attributes_for 的 find_or_create 方式

hardywu · November 15, 2013 · Last by hardywu replied at January 25, 2014 · 8145 hits

update 完美解决 http://wuinm.com/notes/2014/01/24/selective-save-or-update-for-nested-attribute-updating-in-rails.html

= = = = = = = == == = =

类似的问题 http://stackoverflow.com/questions/3579924/accepts-nested-attributes-for-with-find-or-create

accepts_nested_attributes_for : aliases

怎么样实现创建 aliases 的时候是 find_or_create 模式,从而确保不重复创建。stackoverflow 只给出了单个的形式,而且在 mongoid 下没法实现。

可以的,我以前搞过,不过怎么弄的现在记不清了

#1 楼 @huacnlee 给跪了。求函数名。都花了快 7 小时了。

我觉得这算是 mongoid 的问题,直接上 github 发 Issue 了。

有必要一定要用 nested_attributes 实现吗?

foo = Foo.create params[:foo]
params[:foo][:aliases].each { |alias_params| foo.aliases.find_or_create_by(alias_params) }

#4 楼 @Rei 因为用到了 nested_form,必须用 accepts_nested_attributes_for。

#5 楼 @hardywu 给 alias model 加唯一索引,重复写入的时候静默失败。

#6 楼 @Rei 静默失败会影响 model 之间的关联么?

#7 楼 @hardywu 测试一下,我印象中就是没写入,但是实例看不出异常,立即使用可能会有 bug。

奥,不用索引,加唯一校验就行了。

#9 楼 @Rei 我已经加了。。可惜会导致 create 失败。。。。我希望 parent and child models 之间是 n to n 关系。

class Band
  include Mongoid::Document
  embeds_many :albums
  accepts_nested_attributes_for :albums,
    reject_if: ->(attrs){ attrs[:name] == "Violator" }
end

文档碉堡了 http://mongoid.org/en/mongoid/docs/nested_attributes.html

#11 楼 @Rei 能不能不 reject,如果已有 alias 就 update 现有 alias 的 parent_ids ?

#12 楼 @hardywu 如果有这么细致的要求我就用 4 楼的方法了。

#13 楼 @Rei 看来只能按你说的来做。。。。谢了。

accepts_nested_attributes_for :XXX mongoid 必须可以用啊, <%= f.fields_for :XXX,@XXX.XXX.new(:XX => XX, :XX => XX) do |builder| %> ...

#15 楼 @datty258 find_or_create 方式不能。因为设置了 alias 的 name 是 unique,同名保存会出错。。

You need to Sign in before reply, if you don't have an account, please Sign up first.