From 42413235bed80e9af6a9655dba504dbf2bdc572c Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Wed, 10 Jan 2018 21:09:10 +0100 Subject: Adding edit/update logic. The model is not done yet, though. No net on the train. --- src/main.rs | 2 +- src/models.rs | 13 ++++++++++--- src/posts.rs | 20 ++++++++++++++++++++ 3 files changed, 31 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 40fa802..5084fbc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,6 +37,6 @@ fn main() { rocket::ignite() .manage(rocket_blog::init_db_pool()) .mount("/", routes![index, index_json]) - .mount("/posts", routes![posts::new, posts::create, posts::show]) + .mount("/posts", routes![posts::new, posts::create, posts::show, posts::edit, posts::update]) .launch(); } diff --git a/src/models.rs b/src/models.rs index 325ee44..33a5fe7 100644 --- a/src/models.rs +++ b/src/models.rs @@ -2,7 +2,7 @@ use super::schema::posts; use diesel::prelude::*; use diesel::{self, ExecuteDsl}; -#[derive(Serialize, Queryable)] +#[derive(FromForm, Serialize, Queryable)] pub struct Post { pub id: i32, pub title: String, @@ -34,11 +34,18 @@ impl Post { } 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."); } + + pub fn update(_updated_post: &Post, _conn: ::DbConn) { + //use super::schema::posts::dsl::*; + + //diesel::update(updated_post) + // .into(posts) + // .execute(&*conn) + // .expect("Error saving post."); + } } diff --git a/src/posts.rs b/src/posts.rs index a5e2524..859cce5 100644 --- a/src/posts.rs +++ b/src/posts.rs @@ -34,3 +34,23 @@ fn show<'a>(id: i32, conn: ::rocket_blog::DbConn) -> ShowPostTemplate { let p = ::models::Post::get(id, conn); ShowPostTemplate { post: p } } + +#[derive(BartDisplay)] +#[template = "templates/edit_post.html"] +pub struct EditPostTemplate { + post: ::models::Post +} + +implement_responder_for!(EditPostTemplate); + +#[get("//edit", format = "text/html")] +fn edit(id: i32, conn: ::rocket_blog::DbConn) -> EditPostTemplate { + let p = ::models::Post::get(id, conn); + EditPostTemplate { post: p } +} + +#[post("/update", data="")] +fn update(post: Form<::models::Post>, conn: ::rocket_blog::DbConn) -> Redirect { + ::models::Post::update(post.get(), conn); + Redirect::to("/") +} -- cgit v1.2.3