Skip to content

"Set if unset" methods for ActiveValuesΒ #3077

Description

@PacificBird

Motivation

ActiveValues lack a "null coalescing" operation that is common for ORMs in other languages (as well as Options in Rust with unwrap_or). Sometimes you need to set defaults in a model, but only when the field is unset. Currently, that requires making an if block, which is very ugly and verbose.

Proposed Solutions

A pair of new methods on ActiveValue, set_unset, set_unset_with, and set_unset_default, which will work sort of like unwrap_or, unwrap_or_else, and unwrap_or_default respectively.

For an ActiveValue<T>:

fn set_unset(&mut self, val: T) {
    match self {
        ActiveValue::Unset => self.set(val),
        _ => ();
    };
}

fn set_unset_with(&mut self, f: fn() -> T) {
    match self {
        ActiveValue::Unset => self.set(f()),
        _ => ();
    };
}


fn set_unset_default(&mut self)
where 
    T: Default
{
    match self {
        ActiveValue::Unset => self.set(T::default()),
        _ => ();
    };
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Fields

    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions