This is my first "big" Phoenix project, so I decided let here what I did.
I already had this folder created, so I ran:
$ mix local.hex
$ mix archive.install hex phx_new
$ mix phx.new . --app find_your_friend_university --module FindYourFriendUniversity
To create the database:
$ docker run --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres
# Start the container at computer startup
$ docker run --restart=always --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres
To access database
$ psql -h localhost -p 5432 -U postgres -d find_your_friend_university_dev
>>> \dt
>>> SELECT * FROM <table_name>;
If you want, you can store the credentials inside DB_USER
and DB_PASS
env variables and then pass them to Phoenix:
$ read USER
$ read -s PASS
$ DB_PASS=$PASS DB_USER=$USER mix phx.server
I generated my migrations, schemas and all the HTML files with this commands. Then I did some modifications, like turn off some ids that were autogenerated on the migrations and schemas, to receive them on the changeset.
$ mix phx.gen.html Students Student students id:string name:string display_name:string civil_id:string
$ mix phx.gen.html Courses Course courses id:string name:string
$ mix phx.gen.html Universities University universities id:string name:string is_polytechnic:boolean
$ mix phx.gen.html Applications Application applications course_order_num:integer candidature_grade:integer exams_grades:integer _12grade:integer _11grade:integer student_option_number:integer placed:boolean year:integer phase:integer university_id:references:universities course_id:references:courses student_id:references:students
I created a table for the many to many association between Courses and Universities:
$ mix ecto.gen.migration create_universities_courses
And wrote this function on the migrations:
def change do
create table(:universities_courses) do
add :university_id, references(:universities, on_delete: :delete_all, on_update: :update_all, type: :string)
add :course_id, references(:courses, on_delete: :delete_all, on_update: :update_all, type: :string)
end
create unique_index(:universities_courses, [:university_id, :course_id])
end
And then added to Universities and Courses Schema
many_to_many :courses, Course, join_through: "universities_courses" # universities.ex
many_to_many :universities, University, join_through: "universities_courses" # courses.ex
To put the associations on the table while running the changeset, I followed this post.