Enable optional has many relations
mmstick opened this issue · 2 comments
mmstick commented
This can be achieved using a trait:
/// Trait which allows a `has many` relationship to be optional.
pub trait JsonApiArray<M> {
fn get_models(&self) -> &[M];
fn get_models_mut(&mut self) -> &mut [M];
}
impl<M: JsonApiModel> JsonApiArray<M> for Vec<M> {
fn get_models(&self) -> &[M] { self }
fn get_models_mut(&mut self) -> &mut [M] { self }
}
impl<M: JsonApiModel> JsonApiArray<M> for Option<Vec<M>> {
fn get_models(&self) -> &[M] {
self.as_ref()
.map(|v| v.as_slice())
.unwrap_or(&[][..])
}
fn get_models_mut(&mut self) -> &mut [M] {
self.as_mut()
.map(|v| v.as_mut_slice())
.unwrap_or(&mut [][..])
}
}And then changing the macro to generate:
fn build_relationships(&self) -> Option<Relationships> {
let mut relationships = HashMap::new();
$(
relationships.insert(stringify!($has_one).into(),
Self::build_has_one(&self.$has_one)
);
)*
$(
relationships.insert(
stringify!($has_many).into(),
{
let values = &self.$has_many.get_models();
Self::build_has_many(values)
}
);
)*
Some(relationships)
}lock commented
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.