Search code examples
ruby-on-railsruby-on-rails-4activerecordformbuilder

Updating multiple columns in a joins table in Rails 4


I'm having a bit of trouble getting my code to work -

I have several models - Student, Course, and CourseStudents, a joins table between the two. A Student can be assigned to multiple Courses through the CourseStudents model.

student.rb

has_many :courses, :through => :course_students

course.rb

has_many :students, :through => :course_students

Heres some of the working example in the student sign up form. Let's pretend each student can only sign up for two courses at a time. This form will return the params :courses => ["1","2"] (depending on what was selected, of course).

<%= f.fields_for :courses do |course| %>
     <%= course.collection_select(nil, Course.all, :id, :name) %>
     <%= course.collection_select(nil, Course.all, :id, :name) %>
<% end %>

This is a problem, because to assign courses to a student, Rails is expecting Course objects, not IDs. I am unsure how to convert these IDs into objects on the fly.

If it is helpful, my CourseStudents table is fairly simple. It has a course_id and student_id field. Unfortunately, I do not see how I can go in and iteratively insert a record saying course_id: 1, student_id: 1, course_id: 2, student_id: 1.


TL:DR;

I need a way to do the equivalent of Student.first.courses = [Course.find(1), Course.find(2)] - in other words, pass an object through a selection form instead of an ID, or convert the ID while processing.


Solution

  • Rails provides relation_ids= method for has_many relations (doc). So you can just assign courses ids to a student.

    student.course_ids = [1,2]