Mr H
Mr H

Reputation: 5304

Updated_at in Ecto after Repo.update_all

I need to update my Asset table so I need to do something like this.

from(a in Asset, 
where: a.id == ^asset.id, 
update: [set: [asset_name: "a name"] ]
)
|> Repo.update_all([])

This works fine however the updated_at is not updating.

from the documentation:

Keep in mind this update_all will not update autogenerated fields like the updated_at columns.

So does this mean, I need to pass the time into my query? something like DateTime.utc_now

Thanks

Upvotes: 4

Views: 2190

Answers (1)

NoDisplayName
NoDisplayName

Reputation: 15746

Yes, you need to automatically update the timestamp so it should be something like:

Asset
|> where([a], a.id == ^asset.id)
|> update([set: [asset_name: "a name", updated_at: Timex.now()]])
|> Repo.update_all([])

I use Timex.now() here but I guess DateTime.utc_now() will work just as fine but I have not tested it.

If you do that often, I would probably create a generic function that accepts a query and adds the timestamp update to it and returns the updated query.

Upvotes: 5

Related Questions