sgrif / diesel.rs-website

MIT License
32 stars 97 forks source link

Fix insert_into statement #170

Closed timhoeppner-antec closed 2 years ago

timhoeppner-antec commented 2 years ago

The existing diesel::insert_into(posts::table)... requires adding the HasTable trait which just further causes issues.

weiznich commented 2 years ago

Thanks for opening this PR.

The old code on the web page is correct and tested as part of the diesel repository (See the linked code). I assume you see the error you got because you have a use crate::schema::posts::dsl::* somewhere. The example does not have such an import, therefore this change would break the example.

timhoeppner-antec commented 2 years ago

Interesting, I don't have that statement.

Here's my code for reference (slightly adapted to something I was working on).

use diesel::prelude::*;
use diesel::PgConnection;
use uuid::Uuid;
use crate::applications;
use crate::models::{Application, NewApplication};

pub fn create_application(conn: &PgConnection, app_name: &str) -> Application {
    let new_application = NewApplication {
        id: Uuid::new_v4(),
        name: app_name
    };

    diesel::insert_into(applications)
        .values(&new_application)
        .get_result(conn)
        .expect("Error saving new application")
}
timhoeppner-antec commented 2 years ago

My apologies, I just realized I had use crate::schema::applications::dsl::*; in main.rs and was importing the applications from that instead of schema::applications.

weiznich commented 2 years ago

Thanks for coming back and confirming that this fixed your issue. As a general advice: Try to use use crate::schema::some_table::dsl::* only at function level scope, not in modules itself. That avoids such problems.