aboutsummaryrefslogtreecommitdiffstats
path: root/src/models.rs
blob: 325ee44a5b1b785b06a4494bf5589c388417f65d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use super::schema::posts;
use diesel::prelude::*;
use diesel::{self, ExecuteDsl};

#[derive(Serialize, Queryable)]
pub struct Post {
    pub id: i32,
    pub title: String,
    pub body: String,
    pub published: bool,
}

#[derive(Default, FromForm, Insertable)]
#[table_name="posts"]
pub struct NewPost {
    pub title: String,
    pub body: String,
    pub published: bool,
}

impl Post {
    pub fn get_all(conn: ::DbConn) -> Vec<Post> {
        use super::schema::posts::dsl::*;
        posts.filter(published.eq(false))
            .limit(5)
            .load::<Post>(&*conn)
            .expect("Error loading posts")
    }

    pub fn get(post_id: i32, conn: ::DbConn) -> Post {
        use super::schema::posts::dsl::*;
        posts.find(post_id).get_result(&*conn)
            .expect(&format!("Unable to find post with id={}", post_id))
    }

    pub fn create(new_post: &NewPost, conn: ::DbConn) {
        use super::schema::posts;

        diesel::insert(new_post)
            .into(posts::table)
            .execute(&*conn)
            .expect("Error saving post.");
    }
}