Reputation: 13211
When a new user registers, I would like to give him an gravatar profile image by default, afterwards he should be able to set it manually, so the changeset method should only apply if profile_img_url is nil
def changeset(model, params \\ :empty) do
model
|> cast(...)
...
|> get_gravatar
end
defp get_gravatar(current_changeset) do
case current_changeset do
%Ecto.Changeset{valid?: true, *is_nil:* :profile_img_url} ->
put_change(current_changeset, :profile_img_url, get_somehow_the_gravatar_img(current_changeset))
_ -> current_changeset
end
end
So basically, the question is, is this the right way to do it, and is there an Ecto mehtod to check if the value is nil or not. (Not only in the changeset, but also in the db)
Upvotes: 2
Views: 217
Reputation: 13211
Found a solution, but I'll not mark it as accepted, to let other people make a better suggestion.
defp get_gravatar(current_changeset) do
case current_changeset do
%Ecto.Changeset{valid?: true, model: %{profile_img_url: nil, email: email}} ->
put_change(current_changeset, :profile_img_url, to_string(Gravatar.new(email)) <> "?d=identicon")
_ -> current_changeset
end
end
Upvotes: 2
Reputation: 9109
As per my current understanding your implementation is current, you could use an alternative style of code
def get_gravatar changeset do
if changeset.valid? && !(get_field(changeset, :profile_img_url) |> is_nil ) do
put_change(changeset, :profile_img_url, get_gravatar_image)
else
changeset
end
end
Upvotes: 2