Skip to main content

DeriveIntoActiveModel

Derive Macro DeriveIntoActiveModel 

Source
#[derive(DeriveIntoActiveModel)]
{
    // Attributes available to this derive:
    #[sea_orm]
}
Available on crate feature macros only.
Expand description

Will implement [IntoActiveModel] for a struct, allowing conversion into an ActiveModel. This is useful for “form” or “input” structs (like from API requests) that turn into an entity’s ActiveModel but may omit some fields or provide optional values with defaults.

§Usage:

use sea_orm::entity::prelude::*;

#[derive(DeriveIntoActiveModel)]
#[sea_orm(active_model = "fruit::ActiveModel")]
struct NewFruit {
    name: String,
    // `id` and `cake_id` are omitted - they become `NotSet`
}

§set/fill(...) - always set absent ActiveModel fields

use sea_orm::entity::prelude::*;

#[derive(DeriveIntoActiveModel)]
#[sea_orm(active_model = "fruit::ActiveModel", set(cake_id = "None"))]
struct NewFruit {
    name: String,
    // `cake_id` is not on the struct, but will always be `Set(None)`
}

§default = "expr" - fallback for Option<T> struct fields

use sea_orm::entity::prelude::*;

#[derive(DeriveIntoActiveModel)]
#[sea_orm(active_model = "fruit::ActiveModel")]
struct UpdateFruit {
    /// `Some("Apple")` -> `Set("Apple")`, `None` ->`Set("Unnamed")`
    #[sea_orm(default = "String::from(\"Unnamed\")")]
    name: Option<String>,
}

§Combining set(...), default, ignore, and exhaustive

use sea_orm::entity::prelude::*;

#[derive(DeriveIntoActiveModel)]
#[sea_orm(active_model = "fruit::ActiveModel", exhaustive, set(cake_id = "None"))]
struct NewFruit {
    id: i32,
    #[sea_orm(default = "String::from(\"Unnamed\")")]
    name: Option<String>,
}