diff options
author | Harald Eilertsen <haraldei@anduin.net> | 2017-12-23 18:31:51 +0100 |
---|---|---|
committer | Harald Eilertsen <haraldei@anduin.net> | 2017-12-23 18:31:51 +0100 |
commit | e7f487094a9a9202b20bcba471b79fb522d4c44a (patch) | |
tree | 8a1d8c8f4008e33ccc6d2d03cbf09e924662a14e | |
parent | f91bc37b14ec958f67e217ffa65cdf98b8f7417d (diff) | |
download | rocket-blog-e7f487094a9a9202b20bcba471b79fb522d4c44a.tar.gz rocket-blog-e7f487094a9a9202b20bcba471b79fb522d4c44a.tar.bz2 rocket-blog-e7f487094a9a9202b20bcba471b79fb522d4c44a.zip |
Move creating post in db to Post model impl.
-rw-r--r-- | src/main.rs | 2 | ||||
-rw-r--r-- | src/models.rs | 24 | ||||
-rw-r--r-- | src/posts.rs | 9 |
3 files changed, 19 insertions, 16 deletions
diff --git a/src/main.rs b/src/main.rs index ed1d72a..fe8bcab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,7 @@ extern crate rocket_contrib; #[macro_use] extern crate bart_derive; #[macro_use] extern crate serde_derive; -use self::rocket_blog::{schema, models}; +use self::rocket_blog::models; use rocket_contrib::Json; mod posts; diff --git a/src/models.rs b/src/models.rs index ffa07c4..325ee44 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,5 +1,6 @@ use super::schema::posts; use diesel::prelude::*; +use diesel::{self, ExecuteDsl}; #[derive(Serialize, Queryable)] pub struct Post { @@ -9,6 +10,14 @@ pub struct Post { 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::*; @@ -23,12 +32,13 @@ impl Post { posts.find(post_id).get_result(&*conn) .expect(&format!("Unable to find post with id={}", post_id)) } -} -#[derive(Default, FromForm, Insertable)] -#[table_name="posts"] -pub struct NewPost { - pub title: String, - pub body: String, - pub published: bool, + 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."); + } } diff --git a/src/posts.rs b/src/posts.rs index a9cbcf1..a5e2524 100644 --- a/src/posts.rs +++ b/src/posts.rs @@ -1,6 +1,5 @@ use rocket::request::Form; use rocket::response::Redirect; -use diesel::{self, ExecuteDsl}; #[derive(BartDisplay)] #[template = "templates/new_post.html"] @@ -18,13 +17,7 @@ fn new<'a>(_conn: ::rocket_blog::DbConn) -> NewPostTemplate<'a> { #[post("/create", data="<post>")] fn create(post: Form<::models::NewPost>, conn: ::rocket_blog::DbConn) -> Redirect { - use ::schema::posts; - - diesel::insert(post.get()) - .into(posts::table) - .execute(&*conn) - .expect("Error saving post."); - + ::models::Post::create(post.get(), conn); Redirect::to("/") } |