Hey everyone I was wondering how you all handle processing actions that need to take place in a save rather than a validate live view event.
So far I’ve seen passing-in opts such as the one below, but I was wondering if there are better alternatives.
def update_event(%Event{} = event, attrs) do
event
|> Event.changeset(attrs, set_timezone: true)
|> Repo.update()
end
Should I make 2 different changesets?
def update_event(%Event{} = event, attrs) do
event
|> Event.save_changeset(attrs, set_timezone: true)
|> Repo.update()
end
Should I pass in an action: :save
def update_event(%Event{} = event, attrs) do
event
|> Event.changeset(attrs, action: :save)
|> Repo.update()
end
Would love some advice because I feel like there’s a lot of overhead to manage these different actions. Espeically when I have to handle quite a bit of changesets for the event as is since an admin, org_member, or submitter can submit these things.
ie:
def proposal_changeset(event, attrs, opts \\ []) do
event
|> cast(attrs, [
:title,
:hosted_by,
:starts_at,
:place_name,
:event_url,
:is_paid,
:status
])
|> validate_required([
:title,
:hosted_by,
:starts_at,
:place_name,
:event_url,
:status
])
|> required_manipulations(attrs, event, opts)
end
def maybe_change_timezone(changeset, field, location, opts) do
defp required_manipulations(changeset, attrs, _event, opts) do
changeset
|> maybe_put_assoc(:admin, attrs)
|> maybe_put_assoc(:organization, attrs)
|> maybe_put_assoc(:org_member, attrs)
|> maybe_put_assoc(:location, attrs)
|> maybe_change_timezone(:starts_at, attrs["location_id"], opts)
|> maybe_change_timezone(:ends_at, attrs["location_id"], opts)
|> validate_url(:event_url)
|> validate_length(:title, max: 45)
end
def maybe_change_timezone(changeset, field, location, opts) do
if opts[:change_tz] do
shifted_time =
get_change(changeset, field)
|> DateTime.to_naive()
|> DateTime.from_naive!(location.timezone)
|> DateTime.shift_zone!("Etc/UTC")
put_change(changeset, field, shifted_time)
else
changeset
end
end
After two years I still feel like an absolute newbie when it comes to handling changesets and associations…
Thanks in advance