Search code examples
rustormtraitsrust-diesel

rust diesel Associations and Identifiable give "use of undeclared crate or module" error


I have this struct:

#[derive(Queryable,Associations,Identifiable)]
#[diesel(belongs_to(User))]
#[diesel(belongs_to(Task))]
pub struct UserTask{
    pub id:i32,
    pub user_id:i32,
    pub task_id:i32
}

I implement a method

pub struct TaskRepository;
impl TaskRepository{
    
    pub async fn find_by_user(c:&mut AsyncPgConnection,user:&User)->QueryResult<Vec<Task>>{
        let user_tasks = UserTask::belonging_to(&user).get_results::<UserTask>(c).await?;
        let task_ids: Vec<i32> = user_tasks.iter().map(|ut: &UserTask| ut.task_id).collect();         

    }

to be able to use belonging_to(&user), I used Associations and Identifiable traits for UserTask. but this gives me this error:

failed to resolve: use of undeclared crate or module user_tasks

If I remove those traits, error is gone. I could not figure out how to solve the issue.


Solution

  • Both the Associations and Identifiable derive macros require knowing the backing table! definition. By default, this will look for it in scope with a snake-cased and s-suffixed version of the struct name - user_tasks in this case.

    You will either need to bring the name of the backing table! definition into scope and/or use #[diesel(table_name = path::to::table)] above the struct to explicitly tell the derive macros where it is.