加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Build vs Create in有很多关系

发布时间:2020-12-17 02:54:41 所属栏目:百科 来源:网络整理
导读:我想知道是否有人可以帮助我理解Has Many Through(HMT)关系中构建和创建之间的区别? 根据我在阅读stackoverflow和google后的理解,create实际上是build save.但是,似乎create不仅仅是构建save.它还以某种方式保存到HMT关系的连接表中,如下所示. 我创建了3个
我想知道是否有人可以帮助我理解Has Many Through(HMT)关系中构建和创建之间的区别?

根据我在阅读stackoverflow和google后的理解,create实际上是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

然后我在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",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,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","updated_at") VALUES (?,?)[0m  [["body","another one"],["created_at",08 Nov 2014 01:59:39 UTC +00:00],"second title"],08 Nov 2014 01:59:39 UTC +00:00]]
SQL INSERT INTO "collaborators" ("created_at","updated_at","user_id","wiki_id") VALUES (?,?)  [["created_at",["user_id",1],["wiki_id",2]]
=> #<Wiki id:2,title:"second title",body:"another one>

>user.wikis
=> [#<Wiki id: 1,body:"world">,#<Wiki id:2,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不仅仅是构建新的.我对这种行为感到好奇,希望有人可以分享他们的知识.

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读