Ruby on Rails的。如何使用在一个活动记录.build方法:属于关系? [英] Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

查看:337
本文介绍了Ruby on Rails的。如何使用在一个活动记录.build方法:属于关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直无法找到在轨道上.build方法的任何文件(我目前使用2.0.2 AM)。

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

通过实验,似乎可以用构建方法添加一条记录到的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

犬的外键是不是在这种情况下,当出现,当时它被保存的事实,新的人没有一个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?

感谢您

推荐答案

凡有记载:

这是在模块的ActiveRecord下的has_many协会的API文档::协会:: ClassMethods

collection.build(属性= {},...)   返回的一个或多个新对象   对已集合类型   实例化属性和   通过链接到该对象   外键,但尚未得到   保存。注:仅当一个作品   相关对象已经存在,不   如果它是零!

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将它保存的瞬间(很像相应的创造的方法,你可以在集合调用)

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

如何为轨道足够聪明?这是魔术(或者更准确地说,我只是不知道,很想了解一下!)

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

这篇关于Ruby on Rails的。如何使用在一个活动记录.build方法:属于关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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