Hi, I’ve got two schema - Parent & Student. These have many-to-many associations between them.
I’m developing a CRUD app using phoenix. I’ve already created a form to create new Parents and it’s working well.
I wish to provide another form which will enable the user to create a Student record. However, from within this form (or a pop-up modal form), I wish to have the something that allows me to click-select and associate the Student record I’m creating with one/two existing Parent records.
Could someone please suggest a facility within Phoenix/Ecto that readily provides this, if it exists? Or what would you recommend as best practice for such a use case.
Any help would be greatly appreciated.
Welcome to the community.
I don’t think phoenix have out of the box many to many like this.
What I’ve done is in situation like this, within the context of your problem, is to have a query to get all students. The controller will pass this list of students to your view and template. It is up to your form template and view to provide a select input for students either multiple or single or whatever with that student list.
Ecto is able to insert via multi or whatever other solution.
I usually make these type of query, listing all students, into a plug since it comes up often enough across controllers.
Thank you so much. I will try this out.
I think I’ve gotten a better idea of what I would like to achieve now. I’ve gotten some screenshots attached as well. I would greatly appreciate any suggestions for the following requirement I’m trying to implement with Phoenix.
I have a DB table-schema like so:
Sponsors <----many-to-many ----> SponsorsStudents <----many-to-many ----> Students
A user creates a few sponsors. Managed to create a form which facillitates this and it’s working well.
It’s henceforth that I’m having issues:
User initiates to create a new Student with “New Student” form.
Clicks “Add Sponsor” to pop-up a ‘modal’, Sponsor selector window
Clicks on a sponsor and clicks “Select Sponsor”
Selected sponsor is listed back in the “New Student” form, with the Sponsor selector form now closed.
- User selects another Sponsor as before (step 4 onwards), to now have 2 sponsors listed in the “New Student” registration form
- Upon clicking Submit (of the New Student form), the controller should create a new student record in the Students table along with ‘relating’ records in the SponsorsStudents table.
What is the best practice of achieving this? I’m really at my wits end. I am fairly new with Elixir and more so with Phoenix/Ecto. Been reading the Programming Phoenix & Programming Ecto books as well but to no avail, or I’m just not seeing it. Any suggestions please?
Note: I’ve avoided using a select input in the New Student form as I’d like to provide the ability of searching for particular sponsors, to the user, before the user can select and assign the sponsor to the student.