Add a model for posts
parent
0e24b3cdb7
commit
268607da0e
@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
DROP TABLE posts;
|
@ -0,0 +1,10 @@
|
||||
-- Your SQL goes here
|
||||
CREATE TABLE posts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
blog_id INTEGER REFERENCES blogs(id) ON DELETE CASCADE NOT NULL,
|
||||
slug VARCHAR NOT NULL,
|
||||
title VARCHAR NOT NULL,
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
published BOOLEAN NOT NULL DEFAULT 'f',
|
||||
license VARCHAR NOT NULL DEFAULT 'CC-0'
|
||||
)
|
@ -1,4 +1,5 @@
|
||||
pub mod blog_authors;
|
||||
pub mod blogs;
|
||||
pub mod instance;
|
||||
pub mod post;
|
||||
pub mod user;
|
||||
|
@ -0,0 +1,42 @@
|
||||
use diesel;
|
||||
use diesel::{PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods};
|
||||
use schema::posts;
|
||||
|
||||
#[derive(Queryable, Identifiable)]
|
||||
pub struct Post {
|
||||
pub id: i32,
|
||||
pub blog_id: i32,
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
pub content: String,
|
||||
pub published: bool,
|
||||
pub license: String
|
||||
}
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[table_name = "posts"]
|
||||
pub struct NewPost {
|
||||
pub blog_id: i32,
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
pub content: String,
|
||||
pub published: bool,
|
||||
pub license: String
|
||||
}
|
||||
|
||||
impl Post {
|
||||
pub fn insert (conn: &PgConnection, new: NewPost) -> Post {
|
||||
diesel::insert_into(posts::table)
|
||||
.values(new)
|
||||
.get_result(conn)
|
||||
.expect("Error saving new post")
|
||||
}
|
||||
|
||||
pub fn get(conn: &PgConnection, id: i32) -> Option<Post> {
|
||||
posts::table.filter(posts::id.eq(id))
|
||||
.limit(1)
|
||||
.load::<Post>(conn)
|
||||
.expect("Error loading post by id")
|
||||
.into_iter().nth(0)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue