Database schema and models

Comments will be stored in a comments table that has three fields: the id of a comment, the uid of a user, and the text of a comment:

mod schema {
table! {
comments {
id -> Nullable<Integer>,
uid -> Text,
text -> Text,
}
}
}

The Comment struct has the following declaration:

#[table_name="comments"]
#[derive(Serialize, Queryable, Insertable, Debug, Clone)]
pub struct Comment {
pub id: Option<i32>,
pub uid: String,
pub text: String,
}

We repeated the same field in the Comment struct and added the NewComment struct without id:

#[derive(FromForm)]
pub struct NewComment {
pub uid: String,
pub text: String,
}

And now for something new—we derive the FormForm type for the NewComment struct. It helps Rocket convert a query into a Form instance. The next Comment struct implementation adds two methods:

impl Comment {
pub fn all(conn: &SqliteConnection) -> Vec<Comment> {
all_comments.order(comments::id.desc()).load::<Comment>(conn).unwrap()
}

pub fn insert(comment: NewComment, conn: &SqliteConnection) -> bool {
let t = Comment { id: None, uid: comment.uid, text: comment.text };
diesel::insert_into(comments::table).values(&t).execute(conn).is_ok()
}
}

We use the generated method with the diesel crate to interact with a database using a Connection instance. If you want to know more about the diesel crate, you can read more in Chapter 8, Interaction to Database with Object-Relational Mapping.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.38.14