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
Changesets are used for creating and modifying your models. A changeset is literally a struct that stores a set of changes (as well as the validation rules.) You pass a changeset to your Ecto Repo to persist the changes if they are valid.
For any company that currently uses Ruby on Rails, Phoenix Framework should be on your radar, because it adds considerable performance gains. To top that off, Phoenix makes it incredibly fast to build web applications.
Ecto is a persistence framework for Elixir. That is a fancy way of saying that we use Ecto to talk to a SQL database. This chapter will introduce you to the very basics of Ecto in the Phoenix context. This means that whenever available, we use functions that were created by Phoenix generators.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With