2014-11-08 62 views
4

我想知道有沒有人能夠幫助我理解在Has Many Through(HMT)關係中構建和創建的區別?建立vs創建有很多直通關係

從我的理解,通過閱讀通過stackoverflow和谷歌,創建本質上是建立+保存。然而,看起來創建不僅僅是構建+保存。它也以某種方式保存到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 

然後,我測試了構建在軌控制檯創建行爲:

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

案例wiki1:建立並保存它 的數據不會保存到連接表。調用user.wikis會返回對象wiki,但運行user.wikis.count返回0.此外,運行wiki1.users不會返回對象用戶。檢查連接表協作者返回空數組。

案例wiki2:創建 數據被保存到連接表中。調用user.wikis確實會返回對象wiki。運行user.wikis.count返回1.此外,運行wiki1.users確實會返回對象用戶。檢查連接表協作者,它確實顯示了清晰映射的關係。

看起來像創建不僅僅是建立+新。我對這種行爲很好奇,希望有人可以分享他們的知識。

+0

[使用具有\ _many:通過並建立]的可能重複(http://stackoverflow.com/questions/9346261/using-has-many-through - 建立) – Substantial 2014-11-08 03:49:31

回答

3

我相信,如果你在第一種情況下不得不代替書面:

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

...你會發現,ActiveRecord的做「全」保存創建也做。按照你寫的方式,你要求ActiveRecord保存新創建的Wiki實例,但不保存關聯。所以它不會在連接表中創建需要的記錄。

+0

謝謝託德的解釋。現在我懂了 :) – Jayzz55 2014-11-08 04:53:14

2

生成+保存相當於在任何關係中創建