Phoenix Changeset

Im reading the phoenix guides and programming phoenix. Im in the ecto and change set parts. Maybe are silly questions but im getting confuse with two things:

1)The first is with changeset in the new action. Why is needed to create a changeset here and pass it to render new.html?, in the docs its said is for consistency with create action (http://www.phoenixframework.org/docs/ecto-models#section-controller-usage), but still im not get it, and then reading furthers, come the others thing.

  1. In new.html there are error_tag to show is where error in the changesets. If i put in iex this
    User.changeset(%User{})
    i get this :

    #Ecto.Changeset<action: nil, changes: %{},
    errors: [name: {“can’t be blank”, [validation: :required]},
    username: {“can’t be blank”, [validation: :required]}], data: #Rumbl.User<>,
    valid?: false>
    So why im not getting the errors when i go to /users/new ?

Strictly speaking, you don’t; it is done just for consistency’s sake. That way new.html always has a changeset in its parameters, and you don’t have to worry about whether or not there is one before using it.

new.html.eex renders form.html and passes in that changeset. in form.html.eex there is this:

  <%= if @changeset.action do %>
    <div class="alert alert-danger">
      <p>Oops, something went wrong! Please check the errors below.</p>
    </div>
  <% end %>

Notice that there is no changeset.action when you do User.changeset(%User{}):

#Ecto.Changeset<action: nil, changes: %{},

… and so it does not render the error.

2 Likes

Thx, so to see if i get it right ,according to this Phoenix why not show changeset errors? and this Phoenix.HTML.Form has two errors fields when validating?. The form_for helper receive the changeset, check if there is a action, is there is a action, put the errors of the source into the error field of the form and if there is not action, just leave that field empty. So when error_tag is called, check in the error field of the form?

That’s pretty much it … :slight_smile:

1 Like