我想知道有沒有人能夠幫助我理解在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
確實會返回對象用戶。檢查連接表協作者,它確實顯示了清晰映射的關係。
看起來像創建不僅僅是建立+新。我對這種行爲很好奇,希望有人可以分享他們的知識。
[使用具有\ _many:通過並建立]的可能重複(http://stackoverflow.com/questions/9346261/using-has-many-through - 建立) – Substantial 2014-11-08 03:49:31