gpt4 book ai didi

ruby-on-rails - Ruby on Rails。如何在 :belongs to relationship? 中使用 Active Record .build 方法

转载 作者:行者123 更新时间:2023-12-03 04:31:00 25 4
gpt4 key购买 nike

我一直无法找到有关 Rails 中 .build 方法的任何文档(我目前使用的是 2.0.2)。

通过实验,您似乎可以在保存任一记录之前使用构建方法将记录添加到 has_many 关系中。

例如:

class Dog < ActiveRecord::Base
has_many :tags
belongs_to :person
end

class Person < ActiveRecord::Base
has_many :dogs
end

# rails c
d = Dog.new
d.tags.build(:number => "123456")
d.save # => true

这将正确保存带有外键的狗和标签。这似乎不适用于 belongs_to 关系。

d = Dog.new
d.person.build # => nil object on nil.build

我也尝试过

d = Dog.new
d.person = Person.new
d.save # => true

在这种情况下,Dog 中的外键未设置,因为在保存时,新人没有 id,因为它尚未保存。

我的问题是:

  1. 构建如何工作,以便 Rails 足够智能,找出如何以正确的顺序保存记录?

  2. 如何在 belongs_to 关系中做同样的事情?

  3. 在哪里可以找到有关此方法的任何文档?

谢谢

最佳答案

记录在哪里:

来自“Module ActiveRecord::Associations::ClassMethods ”中 has_many 关联下的 API 文档

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

以相反方向构建的答案是稍微改变语法。在你与狗的例子中,

Class Dog
has_many :tags
belongs_to :person
end

Class Person
has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

甚至

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

您还可以使用 create_dog 立即保存它(非常类似于您可以在集合上调用的相应“create”方法)

rails 如何足够智能?这很神奇(或者更准确地说,我只是不知道,很想知道!)

关于ruby-on-rails - Ruby on Rails。如何在 :belongs to relationship? 中使用 Active Record .build 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/783584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com