2

I have 2 ecto schema models that have a man_to_many relationship.

schema "Users" do

  many_to_many :locations, Location, join_through: "locations_users"
end

schema "Locations" do
  many_to_many :users, User, join_through: "locations_users"
end

So in my User.ex schema model file how should I go about writing a function to add and also to remove a user?

def add_location(location) do
  # ???
end

def remove_location(location) do
  # ???
end

In the ecto docs it says you shouldn't have to load all the associated data before adding/removing an association item, you can just set the association. But since I am using a many to many, I'm not sure how I can just set the association since it is a join table only.

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • If you want to work with the whole association, you use `cast_assoc`, if you want to work with partial or transform before saving, you use `put_assoc`. I think that is what is mentioned in the docs. Where is your user having the locations since it is to him you associate the given locations.? – franckstifler Jan 09 '19 at 21:45
  • I have a similar problem https://stackoverflow.com/questions/54369243/many-to-many-with-ecto-and-put-assoc-4 – Nuno_Coletiv Jan 25 '19 at 16:56

0 Answers0