8
votes

I want to set default values for a model in Phoenix Framework, I have tried:

  def new(conn, _params) do

    user = get_session(conn, :user)
    if is_nil user do
        user = Repo.get_by(User, name: "guest")
        conn = put_session(conn, :user, user)
    end

    changeset = Module.changeset(%Module{})

    changeset
    |> Ecto.Changeset.put_change(:user, user)
    |> Ecto.Changeset.put_change(:version, "0.0.0")
    |> Ecto.Changeset.put_change(:visibility, "public")

    render(conn, "new.html", user: user, changeset: changeset)
  end

How do I set default values in the model so they appear when new.html is rendered?

BTW, here is my default changeset function. I couldn't figure out how to use it? I'm assuming use a Ecto.changeset.put_change in the pipeline after the cast?

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
1

1 Answers

7
votes

There are several ways depending on your changeset function (which you haven't provided here.)

You could do:

changeset = Module.changeset(%Module{user: user, version: "0.0.0", visibility: "public"})

Another option is to pass the parameters to your changeset function:

changeset = Module.changeset(%Module{}, %{user: user, version: "0.0.0", visibility: "public"})

However it is important to note that your version with the put_change/3 function will also work, if you bind the result of your pipeline:

Change:

changeset = Module.changeset(%Module{})

changeset
|> Ecto.Changeset.put_change(:user, user)
|> Ecto.Changeset.put_change(:version, "0.0.0")
|> Ecto.Changeset.put_change(:visibility, "public")

To:

changeset =
  Module.changeset(%Module{})
  |> Ecto.Changeset.put_change(:user, user)
  |> Ecto.Changeset.put_change(:version, "0.0.0")
  |> Ecto.Changeset.put_change(:visibility, "public")

Another option is to set the default at the database level in your migration. If you look at the :default option of Ecto.Migration.add/3 you will see how to do this.