【发布时间】:2015-01-04 22:55:05
【问题描述】:
我想知道是否有人可以帮助我了解在 Has Many Through (HMT) 关系中构建和创建之间的区别?
根据我阅读stackoverflow和google后的理解,创建本质上是构建+保存。但是,似乎 create 不仅仅是构建 + 保存。它还以某种方式保存到 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 控制台中测试了构建和创建行为:
$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 不会返回对象用户。检查连接表 Collaborator 返回空数组。
案例 wiki2:创建
数据被保存到连接表中。调用 user.wikis 确实会返回对象 wiki。运行 user.wikis.count 返回 1。此外,运行 wiki1.users 确实返回对象用户。检查连接表 Collaborator,它确实显示了清晰映射的关系。
似乎 Create 不仅仅是简单的 build + new。我对这种行为很好奇,希望有人能分享他们对此的了解。
【问题讨论】:
标签: ruby-on-rails model-associations