I'm working through the Disel's getting started demo, but adding associations with a user who can post. When I try to use the belonging_to() function it gives the following error:
no function or associated item named
belonging_tofound for structdiesel_demo::models::Postin the current scope function or associated item not found indiesel_demo::models::Post
I used the Associations macro on the struct, and I thought that was enough to get the belonging_to function working, but I'm missing something.
Here is a simple query where I try to use belonging_to(), but this fails.
#[macro_use] extern crate diesel_demo;
use diesel::prelude::*;
use crate::diesel_demo::*;
use crate::diesel_demo::models::*;
fn main() {
use diesel_demo::schema::posts::dsl::*;
use diesel_demo::schema::users::dsl::*;
let connection = establish_connection();
let test_id = 2;
let user = users.find(test_id).first::<User>(&connection).expect("error getting user");
let post_list = Post::belonging_to(&user)
.load::<Post>(&connection)
.expect("Error loading user posts");
println!("{:?}", post_list);
}
And here is the models.rs file where the structs live.
use super::schema::{posts, users};
#[derive(Identifiable, Queryable, PartialEq, Debug)]
#[diesel(table_name = users)]
pub struct User {
pub id: i32,
pub name: String,
}
#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser<'a>{
pub name: &'a str,
}
#[derive(Identifiable, Associations, Queryable, PartialEq, Debug)]
#[diesel(belongs_to(User))]
pub struct Post {
pub id: i32,
pub user_id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
#[derive(Insertable)]
#[table_name = "posts"]
pub struct NewPost<'a>{
pub user_id: &'a i32,
pub title: &'a str,
pub body: &'a str,
pub published: &'a bool,
}
This is from cargo check:
error[E0599]: no function or associated item named `belonging_to` found for struct `diesel_demo::models::Post` in the current scope
--> src/bin/publish_post.rs:18:27
|
18 | let post_list = Post::belonging_to(&user)
| ^^^^^^^^^^^^ function or associated item not found in `diesel_demo::models::Post`