首页 文章

Build vs Create in有很多关系

提问于
浏览
4

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

从阅读stackoverflow和google后的理解, create is essentially build + save . 但是,似乎create不仅仅是构建save . 它还以某种方式保存到HMT关系的连接表中,如下所示 .

我创建了3个模型:用户,wiki和协作者 .

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

然后我测试了构建并在_1511276中创建行为:

$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>

Case wiki1 : build and then save it 数据未保存到连接表中 . 调用 user.wikis 会返回对象wiki,但运行 user.wikis.count 会返回0.此外,运行 wiki1.users 不会返回对象用户 . 检查连接表Collaborator返回空数组 .

Case wiki2 : create 数据已保存到连接表中 . 调用 user.wikis 会返回对象wiki . 运行 user.wikis.count 返回1.此外,运行 wiki1.users 会返回对象用户 . 检查连接表Collaborator,它确实显示了清晰映射的关系 .

似乎Create不仅仅是构建新的 . 我对这种行为感到好奇,希望有人可以分享他们的知识 .

2 回答

  • 2

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

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

    ...你会发现ActiveRecord执行创建的“完整”保存 . 你编写它的方式,你要求ActiveRecord保存新创建的Wiki实例,而不是关联 . 因此它不会在连接表中创建所需的记录 .

  • 3

    Build Save等同于在任何关系中创建

相关问题