Elixir Tips

Elixir Tips

  • You can validate a field based on if it's in memory or persisted. Use Ecto.get_meta/2 to check for the state of the struct https://hexdocs.pm/ecto/Ecto.Schema.Metadata.html h/t to @sleeplessgeek
    import Ecto.Changeset
    
    def ensure_hostname_is_permanent(changeset) do
      state = Ecto.get_meta(changeset, :state)
    
      # state will be :built (in memory), :loaded (persisted), or :deleted (on its way out)
    
      if get_change(changeset, :hostname) && state != :built do
        add_error(changeset, :hostname, "Cannot change hostname after persisting")
      else
        changeset
      end
    end
    31 upvotes