Preload associations

ecto

#1

I have many to many associations between facilities and users:

schema "facilities" do         
field(:name, :string)
field(:description, :string)
field(:is_active, :boolean, default: true)


many_to_many(:users, User, join_through: "users_facilities")
end

schema "users_facilities" do
belongs_to(:user, User, primary_key: true)
belongs_to(:facility, Facility, primary_key: true)
end

schema "users" do
field(:first_name, :string)
field(:last_name, :string)
field(:email_address, :string)
field(:username, :string)
many_to_many(:facilities, Facility, join_through: 
"users_facilities")

I want to preload associated users with the particular facility

When I do

 Repo.preload(facility, :users). 

The users list is empty?
Am I doing something wrong?
Thanks


#2

First thing, you don’t need the below schema if you’re using join_through: "users_facilities" If you still want to use it you need to refer to the module join_through: UserFacility

Second, did you check your database to make sure the join table contains the user and facility ids?


#3

Hey thanks for your reply. I was making some mistake while inserting, Its working now. Thanks