From c427e4e89bdff1f6589d43830d7b85ebe5345cf8 Mon Sep 17 00:00:00 2001 From: Sam Samai Date: Sun, 12 Sep 2021 19:21:01 +1000 Subject: [PATCH] Edit post --- examples/actix_example/src/main.rs | 43 ++++++++++++++++ .../actix_example/templates/edit.html.tera | 50 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 examples/actix_example/templates/edit.html.tera diff --git a/examples/actix_example/src/main.rs b/examples/actix_example/src/main.rs index fd32f0ff..da893dc5 100644 --- a/examples/actix_example/src/main.rs +++ b/examples/actix_example/src/main.rs @@ -94,6 +94,47 @@ async fn create( Ok(HttpResponse::Found().header("location", "/").finish()) } +#[get("/{id}")] +async fn edit(data: web::Data, id: web::Path) -> Result { + let conn = sea_orm::Database::connect(&data.db_url).await.unwrap(); + let template = &data.templates; + + let post: post::Model = Post::find_by_id(id.into_inner()) + .one(&conn) + .await + .expect("could not find post") + .unwrap(); + + let mut ctx = tera::Context::new(); + ctx.insert("post", &post); + + let body = template + .render("edit.html.tera", &ctx) + .map_err(|_| error::ErrorInternalServerError("Template error"))?; + Ok(HttpResponse::Ok().content_type("text/html").body(body)) +} + +#[post("/{id}")] +async fn update( + data: web::Data, + id: web::Path, + post_form: web::Form, +) -> Result { + let conn = sea_orm::Database::connect(&data.db_url).await.unwrap(); + let form = post_form.into_inner(); + + post::ActiveModel { + id: Set(Some(id.into_inner())), + title: Set(form.title.to_owned()), + text: Set(form.text.to_owned()), + } + .save(&conn) + .await + .expect("could not edit post"); + + Ok(HttpResponse::Found().header("location", "/").finish()) +} + #[actix_web::main] async fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_web=info"); @@ -138,4 +179,6 @@ pub fn init(cfg: &mut web::ServiceConfig) { cfg.service(list); cfg.service(new); cfg.service(create); + cfg.service(edit); + cfg.service(update); } diff --git a/examples/actix_example/templates/edit.html.tera b/examples/actix_example/templates/edit.html.tera new file mode 100644 index 00000000..82a178b3 --- /dev/null +++ b/examples/actix_example/templates/edit.html.tera @@ -0,0 +1,50 @@ +{% extends "layout.html.tera" %} {% block content %} +
+

Edit Post

+
+
+
+
+ + +
+
+
+ + + +
+
+
+ +
+
+
+
+
+
+
+ + +
+
+
+
+
+{% endblock content %}