Build vs Create in有很多关系

时间:2014-11-08 03:00:14

标签: ruby-on-rails model-associations

我想知道是否有人可以帮助我理解Has Many Through(HMT)关系中构建和创建之间的区别?

根据我在阅读stackoverflow和google后的理解, create实际上是build + save 。但是,看起来创建不仅仅是构建+保存。它还以某种方式保存到HMT关系的连接表中,如下所示。

我创建了3个模型:用户,维基和协作者。

class User < ActiveRecord::Base
  has_many :wikis, through: :collaborators
  has_many :collaborators
end

class Wiki < ActiveRecord::Base
  has_many :users, through: :collaborators
  has_many :collaborators
end

class Collaborator < ActiveRecord::Base
  belongs_to :user
  belongs_to :wiki
end

然后我在 rails console 中测试了构建和创建行为:

$rails c
Loading development environment (Rails 4.0.10)
> user = User.first  #create instance user
User Load SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 1, name: "Jayzz55">

> (user.wikis.build(title:"hello",body:"world")).save  #build and save wiki
SQL INSERT INTO "wikis" ("body", "created_at", "title", "updated_at") VALUES(?,?,?,?) [["body","world"], ["ccreated_at, Sat, 08 Nov 2014 01:39:36 UTC +00:00], ["title","hello"], ["updated_at",Sat, 08 Nov 2014 01:39:36 UTC +00:00]]
=> true

>wiki1 = Wiki.first  #create instance wiki called wiki1
=> #<Wiki id:1, title:"hello",body:"world">

>user.wikis
=> #<Wiki id:1, title:"hello",body:"world">

>user.wikis.count
=> 0

>wiki1.users
=> []

>Collaborator.all
=> []

> user.wikis.create(title:"second title",body:"another one")
begin transaction
SQL INSERT INTO "wikis" ("body", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?)[0m  [["body", "another one"], ["created_at", Sat, 08 Nov 2014 01:59:39 UTC +00:00], ["title", "second title"], ["updated_at", Sat, 08 Nov 2014 01:59:39 UTC +00:00]]
SQL INSERT INTO "collaborators" ("created_at", "updated_at", "user_id", "wiki_id") VALUES (?, ?, ?, ?)  [["created_at", Sat, 08 Nov 2014 01:59:39 UTC +00:00], ["updated_at", Sat, 08 Nov 2014 01:59:39 UTC +00:00], ["user_id", 1], ["wiki_id", 2]]
=> #<Wiki id:2, title:"second title",body:"another one>

>user.wikis
=> [#<Wiki id: 1, title:"hello",body:"world">, #<Wiki id:2, title:"second title",body:"another one>]

>user.wikis.count
=> 1

>wiki2.users
=>#<User id: 1, name: "Jayzz55">

>Collaborator.all
Collaborator Load SELECT "collaborators".* FROM "collaborators"
=> #<Collaborator id:`, user_id:1, wiki_id: 2>

案例维基1:构建然后保存 数据不会保存到连接表中。调用user.wikis会返回对象wiki,但运行user.wikis.count会返回0.此外,运行wiki1.users不会返回对象用户。检查连接表Collaborator返回空数组。

案例维基2:创建 数据将保存到连接表中。调用user.wikis会返回对象wiki。运行user.wikis.count返回1.此外,运行wiki1.users会返回对象用户。检查连接表Collaborator,它确实显示了清晰映射的关系。

似乎Create不仅仅是build + new。我对这种行为感到好奇,希望有人可以就此分享他们的知识。

2 个答案:

答案 0 :(得分:3)

我相信,如果你在第一个案例中写了:

user.wikis.build(title:"hello",body:"world")
user.save

...你会发现ActiveRecord完成&#34;完整&#34;保存,创建也。你编写它的方式,你要求ActiveRecord保存新创建的Wiki实例,而不是关联。因此,它不会在连接表中创建所需的记录。

答案 1 :(得分:2)

Build + Save相当于以任何关系创建