How to properly Insert data into one-to-many associations

I’m scratching my head because I didn’t get how Ecto works with association.

Supposed I have a one to many relationship between Student and Course Degree.

Student:

schema "students" do
   field :name, :string
   belongs_to :course, Course
   timestamps()
end

def changeset(student, attrs) do
   student
     |> cast(attrs, [:name])
     |> validate_required([:name])
end

Course:

schema "courses" do
  field :name, :string
  has_many :students, Student
  timestamps()
end

def changeset(course, attrs) do
  course
   |> cast(attrs, [:name])
   |> validate_required([:name])
end

Then I have seed data for Course table:

[ID]--------------[Name]
1 -----------------BSCS
2 -----------------BSIT
3 -----------------ACT

Then inserting student data with foreign key relation to Course table I follow what Ecto Associations show.

course = Repo.get(Course, 1) // BSCS
student = %Student{name:"John Doe", course: course}
Repo.insert(student)

My question is do I really have to get the course by id to be assign it to the Student map or can I used just the foreign key id to be persisted together student record.

Like:

student = %Student{name:"John Doe", course: 1}
Repo.insert(student)

Hopefully I get some answers.

Hi,

I am I’m my phone at this moment but have posted about this issue. Maybe this post can help:

Best regards,

Just use course_id?

student = %Student{name:"John Doe", course_id: 1}
Repo.insert(student)
1 Like