Build vs Create in has many cross-cutting relationships

I wonder if someone can help me figure out the difference between building and building in the relationship between many (HMT)?

From my understanding, after reading stackoverflow and google, create essentially builds + save . However, the creation seems to do more than just create + save. It also somehow stores the HMT relationships in the join table, as shown below.

I created 3 models: user, wiki and collaborator.

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

Then I tested the build and create behavior in the rails console :

$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 return 0. , wiki1.users . Collaborator .

wiki2: . user.wikis wiki. user.wikis.count return 1. , wiki1.users . Collaborator, , .

, Create build + new. , , , - .

+4
2

, :

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

... , ActiveRecord "" , . , ActiveRecord Wiki, . .

+3

Build + Save Create

+2

All Articles