Search code examples
elixirphoenix-frameworkecto

How to Update a Model's Boolean Attribute From Terminal


I've got a boolean attribute on a Users model in my Phoenix application.

How can I update this attribute from my terminal/command prompt?

For example - in the Rails console (running rails c in my terminal) I can do something like this:

u = User.find(1)

u.admin = true

u.save

What's the best way to do this in Phoenix? (through iex -S mix maybe? - I think that's the closest thing to the rails c).


Solution

  • You are correct that iex -S mix will open a console.

    You have to use an Ecto.Changeset struct to make the change. Ecto.Changeset.change/2 is the easiest way to make arbitrary changes:

    alias MyApp.{Repo, User} # for convenience, not required
    user = Repo.get(User, 1)
    Ecto.Changeset.change(user, %{admin: true}) |> Repo.update!
    

    Note that if you want to run your users validations when doing updates like this, you will probably want to use the function defined in your model (changeset/2 by default).