Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reload an ecto record?

Tags:

elixir

ecto

I have this code to insert a record into the database. After doing this, I need to get the new record's id to pass to the client.

  msg_record = %Message{
    fromEmail: params["fromEmail"],
    body: params["body"],
    room: room_id
  }
  Repo.insert!(msg_record)

The problem is, after doing this msg_record.id is still null.

In Rails I would do msg_record.reload.id - is there some equivalent method?

like image 324
max pleaner Avatar asked Mar 11 '23 00:03

max pleaner


1 Answers

I guess I didn't look well enough at the docs.

This is found in the HexDocs on Ecto:

iex> weather = %Weather{temp_lo: 0, temp_hi: 23}

iex> Repo.insert!(weather)

After persisting weather to the database, it will return a new copy of %Weather{} with the primary key (the id) set. We can use this value to read a struct back from the repository:

So in my case, I can simply reassign the varaible:

msg_record = Repo.insert!(msg_record)
like image 156
max pleaner Avatar answered Mar 19 '23 19:03

max pleaner