【发布时间】:2015-05-27 16:21:47
【问题描述】:
我试图实现first_or_build 方法,但在保存我的父母时遇到了一个问题:孩子们失踪了。
当我在 parent.childs.first_or_build(name: 'Foo'); parent.save! 这样的关系上调用我的方法时,一切正常,而当我调用 parent.childs.where(name: 'Foo').first_or_build; parent.save! 时没有任何反应。
主要目标是提出与.first_or_create 类似的行为,例如应用于查询结果。 (不要告诉我.first_or_initialize!)
有什么想法吗?
例子:
# this is not working :(
2.times { |i| parent.childs.where(name: "child #{i}").build { |c| c.age = 42 } } ; parent.childs
=> #<ActiveRecord::Associations::CollectionProxy []>
# while this is
2.times { |i| parent.childs.build { |c| c.name = "#{child #{i}"; c.age = 42 } } ; parent.childs
=> #<ActiveRecord::Associations::CollectionProxy [#<Child name: "child 0", age: 42>, #<Child name: "child 1", age: 42>]>
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 activerecord associations