Why does Repo.get(User, 1).id work but Repo.insert!(User).id not?

I don’t like this syntax, but a developer I’m working with who is new to Elixir asked me this question and I didn’t have an answer.

Both get/3 and insert!/2 return Ecto.Schema.t, but only with get/3 does it behave object-like and you can specify an attribute of the struct directly from the get/3 function. This doesn’t work with insert!/2 despite returning the same type - it must first be assigned to a variable:

user = Repo.insert!(User)
user.id
1 Like

Can you paste the code that does not work too?

2 Likes

Oops, nevermind, it does work. :021: picard.jpg

Interactive Elixir (1.4.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> alias Storage.Repo
Storage.Repo
iex(2)> alias Storage.Schema.User
Storage.Schema.User
iex(3)> Repo.get(User, 1).id
[debug] QUERY OK source="user" db=2.2ms decode=12.9ms
SELECT u0."id", u0."email", u0."phone", u0."password_hash", u0."status", u0."inserted_at", u0."updated_at" FROM "user" AS u0 WHERE (u0."id" = $1) [1]
1
iex(4)> Repo.insert!(%User{email: "test@email.com", phone: "123456789", status: "registered", password_hash: "temppass"}).id
[debug] QUERY OK db=0.2ms
begin []
[debug] QUERY OK db=13.3ms
INSERT INTO "user" ("email","password_hash","phone","status","inserted_at","updated_at") VALUES ($1,$2,$3,$4,$5,$6) RETURNING "id" ["test@email.com", "temppass", "123456789", 0, {{2017, 2, 14}, {18, 44, 14, 380716}}, {{2017, 2, 14}, {18, 44, 14, 380724}}]
[debug] QUERY OK db=1.0ms
commit []
2
iex(5)>
2 Likes