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.
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”.
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
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?
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?.