Diesel models issue

This line that specifies the database table name that corresponds to my Dog struct gives the error "use of undeclared crate or module dogs". If I remove that line then I get the same error on the pub struct Dog line. I'm not sure how to fix this. My goal is to get the insert_dog method in main.rs to work.

Add this to the file where the error occurs:

use crate::schema::dogs;
1 Like

That definitely helped! I'm making progress. My next issue is in trying to retrieve all the rows from my "dogs" table. See here: rust-diesel-demo/main.rs at master · mvolkmann/rust-diesel-demo · GitHub
The compiler also does not like the connection I'm passing to the load method. It says "the trait diesel::Connection is not implemented for &diesel::PgConnection".

Is it correct that I need to define one struct for dogs that will be retrieved and another that omits the id field for inserting dogs as shown here? rust-diesel-demo/models.rs at master · mvolkmann/rust-diesel-demo · GitHub

The compiler tells you how to fix this. conn is already a reference, so you don't need to take a reference to it:

  --> src/bin/main.rs:39:22
   |
39 |         .load::<Dog>(&conn)
   |                      -^^^^
   |                      |
   |                      the trait `diesel::Connection` is not implemented for `&diesel::PgConnection`
   |                      help: consider removing the leading `&`-reference

If you want to retrieve the entire row, you don't need a select clause. Try this:

let results = dogs::dsl::dogs
    .load::<Dog>(conn)
    .expect("error loading dogs");

If you want to retrieve only a few columns, you can use a select like this:

let results = dogs::dsl::dogs
    .select((dogs::name, dogs::breed))
    .load::<(String, String)>(conn)
    .expect("error loading dogs");

for (name, breed) in results {
    println!("{} is a {}.", name, breed);
}
1 Like

You can also do something like this:

    diesel::insert_into(dogs::table)
        .values((dogs::name.eq(name), dogs::breed.eq(breed)))
        .execute(conn)

Thanks so much! I need to get better about seeing the suggestions in the compiler messages. The errors come out in red and really catch my attention. The suggestions come out in a kind of dim blue and I sometimes overlook them.