Checking if a changeset is valid and how to get specific values

Hi guys,
I think that i love elixir, and phoenix, it’s so simple to understand the flow of the app and the connection with pipelines, but, i’m hating one thing…

it’s hard for me to understand the pattern matching on a changeset, i mean i have to do the destructuring everytime to get a specific value? or can i use the “.” to access to keys and values? cause i mean, to me it’s more simple than write everytime all the struct, to match and grab a value. :slight_smile:
and to get a simple is_valid value, i have to do a pattern match on the changeset when i could get the is_valid with a key check.

To me it is like, “Don’t use the . to access cause is wrong in functional programming, instead do a pattern match to grab a value”.

thanks.

1 Like

You should be able to access the properties with a dot notation. For example look here:

http://blog.danielberkompas.com/elixir/2015/05/08/testing-ecto-validations.html

def create(conn, params) do
  user = MyApp.User.changeset(%MyApp.User{}, params)

  if user.valid?
    MyApp.Repo.insert(user)
    # return success
  else
    # render error
  end
end

Do you do something similar?

1 Like

cool man!

no, in my case on the phoenix book i bought, it does something like %User{“is_valid” => return_value} = changeset, something like that, and grab that value from the struct.

The point is, i understand that is maybe the best thing to do pattern matching, but it seem like i’m forced to use it instead of the dot syntax.

So if there is no particular reason, is ok if i use the dot syntax?

thanks.

1 Like

If you want to check that a changeset is valid in a function head you normally do it something like:

def some_func(%Ecto.Changeset{valid?: true} = changeset) do
  ...
end

as this allows you to bind a name to the changeset and also perform the validation check in a concise way. You can also bind nested vars this way. e.g.

def some_func(%Ecto.Changeset{valid?: true, changes: %{password: pass}}) do
  ..
end

If you just want to check if a changeset is valid and you are not pattern matching, then yes, you should just check changeset.valid?.

5 Likes

Thank you tyro!

1 Like