Kaynağa Gözat

Bug fix. Create home relationship to user

Lee Morgan 2 ay önce
ebeveyn
işleme
8f0a118ce0
2 değiştirilmiş dosya ile 11 ekleme ve 6 silme
  1. 2 2
      src/controllers/home/create.rs
  2. 9 4
      src/models/home.rs

+ 2 - 2
src/controllers/home/create.rs

@@ -18,8 +18,8 @@ pub async fn route(
     body: web::Json<Body>,
     req: HttpRequest
 ) -> Result<HttpResponse, AppError> {
-    user_auth(&db, &req).await?;
+    let user = user_auth(&db, &req).await?;
     let home = Home::new(body.into_inner().name);
-    home.insert(&db).await?;
+    home.insert(&db, user.id).await?;
     Ok(HttpResponse::Ok().json(home))
 }

+ 9 - 4
src/models/home.rs

@@ -20,13 +20,18 @@ impl Home {
         }
     }
 
-    pub async fn insert(&self, db: &PgPool) -> Result<(), AppError> {
+    pub async fn insert(&self, db: &PgPool, user_id: Uuid) -> Result<(), AppError> {
         sqlx::query!(
-            "INSERT INTO homes (id, name, created_at)
-            VALUES($1, $2, $3)",
+            "WITH _ AS (
+                INSERT INTO homes (id, name, created_at)
+                VALUES ($1, $2, $3)
+            )
+            INSERT INTO users_homes (user_id, home_id, is_admin)
+            VALUES ($4, $1, true)",
             self.id,
             self.name,
-            self.created_at
+            self.created_at,
+            user_id
         )
             .execute(db)
             .await?;