I know this a really simple problem to be stuck on, but I can’t quite work out how to build associations between different models. I know that I need to be using
Ecto.build_assoc/3, and that I need to start from the
I’ve read through the Ecto docs, re-read the relevant sections in Programming Phoenix, and even tried to get the “a-ha!” moment from looking at projects like Phoenix Trello, as it has similar associations.
I’m trying to model a marketplace where a
Conversation happens between a buyer, seller (both
Users), around an
Conversation model is:
schema "conversations" do belongs_to :buyer, Tic.User belongs_to :seller, Tic.User belongs_to :item, Tic.Item end
I suspect my confusion might be caused by having two references to the
How would I go about creating a new
Conversation, from an
Item page. My thought was that when a button is clicked from the page, a
create action on the
ConversationController fires with data about the
Item and using
Repo.preload the Item’s user (the seller). The buyer’s user account could then be picked up from the connection as per Programming Phoenix.
What I’ve been trying in iex thus far has been variations on:
buyer = Repo.get(User, 9) item = Repo.get(Item, 11) item = Repo.preload(item, :user) seller = item.user conversation = Ecto.build_assoc(item, :conversations) conversation = Ecto.build_assoc(buyer, :conversations) conversation = Ecto.build_assoc(seller, :conversations)
I know that’s really messy and convoluted, but I’ve been trying to break everything down as much as possible to work out what’s what. The issue I’m getting is associating the two Users with the Conversation. Do I need to specify how the
Conversation model refers to users somewhere (i.e. “buyer” and “seller”)? Perhaps the Polymorphic Associations from the
belongs_to docs is what I need to be looking at?
Once again, apologies for the probably simple problem, but I’m struggling to get my head round this. Cheers!