Ruby on Rails.如何在 :belongs to 关系中使用 Active Record .build 方法? [英] Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

查看:36
本文介绍了Ruby on Rails.如何在 :belongs to 关系中使用 Active Record .build 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 中找不到任何关于 .build 方法的文档(我目前使用的是 2.0.2).

I have been unable to find any documentation on the .build method in Rails (i am currently using 2.0.2).

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

Through experimentation it seems you can use the build method to add a record into a has_many relationship before either record has been saved.

例如:

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 关系.

This will save both the dog and tag with the foreign keys properly. This does not seem to work in a belongs_to relationship.

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

我也试过

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

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

The foreign key in Dog is not set in this case due to the fact that at the time it is saved, the new person does not have an id because it has not been saved yet.

我的问题是:

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

  1. How does build work so that Rails is smart enough to figure out how to save the records in the right order?

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

How can I do the same thing in a belongs_to relationship?

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

Where can I find any documentation on this method?

谢谢

推荐答案

记录位置:

来自Module ActiveRecord::Associations 中 has_many 关联下的 API 文档::类方法"

collection.build(attributes = {}, ...)返回一个或多个新对象收集类型用属性实例化和通过一个链接到这个对象外键,但还没有保存.注意:这仅适用于关联的对象已经存在,而不是如果它是零!

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!

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

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

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"方法)

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

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

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

这篇关于Ruby on Rails.如何在 :belongs to 关系中使用 Active Record .build 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆