我想在控制器方法中的数据库中执行两个插入操作:
a = A.new(:dog_id => b.id, ...)
a.save
b = B.new(:cat_id => a.id , ... )
b.save
既然我需要 b 中的 a id 和 a 中 b 的 id,我该怎么做?
我想在控制器方法中的数据库中执行两个插入操作:
a = A.new(:dog_id => b.id, ...)
a.save
b = B.new(:cat_id => a.id , ... )
b.save
既然我需要 b 中的 a id 和 a 中 b 的 id,我该怎么做?
首先设置具有正确关联的模型 A + B
Model Cat
has_one :dog
accepts_nested_attributes_for :dog
Model Dog
has_one :cat
accepts_nested_attributes_for :cat
我将模型基于您提供的代码,其中 A 的每个实例只能有一个 B,反之亦然。您也可以使用belongs_to 代替2006 年的旧解释
Accepts_nested_attributes_for 允许您在原始模型的参数中传递关联 模型的属性
在控制器中构建模型的实例并设置它们的关联。
this_cat = Cat.new(cat_attributes{dog_attributes})
this_cat.save!
很确定有几种方法可以做到这一点,但正如阿尔多所说,关于问题代码的更多细节将有助于清除一些关联 - 因为我可能对你希望它如何运作有错误的想法。
不使用 Accepts_nested_attributes_for 的另一种方法是构建 A 和 B 的每个实例,保存其中一个,进行关联,然后保存它们。
this_cat = Cat.new(cat_attributes)
this_dog = Dog.new(dog_attributes)
this_dog.save!
this_cat.dog = this_dog
this_cat.save!
this_dog.save!
甲、乙、丙?你想做什么?如果您有一个Category
包含许多狗的Dog
模型和一个属于某个类别的模型,则您只有类别,当您创建新狗时,您只需使用dog.category = Category.find_by_name(category_name)
.
...但是我怀疑您在狗和类别之间存在某种多对多关系,在这种情况下,您需要另一个模型和数据库表...
更新:对我来说仍然没有任何意义,尝试提供更多细节......另一个想法是创建两个对象然后更新:
# Create the two objects
a = A.create
b = B.create
# Update a with the B id
a.dog = b
a.save
# Update b with the A id
b.cat = a
a.save
但是同样,您应该真正更新您的答案以解释您要达到的目标