简体   繁体   中英

Form creation for a HABTM association

Here's what I'm trying to accomplish. I have courses that students register for. I want to track the advanced students in that class. I set up another model called course_results.

class CourseAdvanceType < ActiveRecord::Base
  belongs_to :course
  has_and_belongs_to_many :students
end

####### 
class Students < ActiveRecord::Base
  has_many :courses
  has_and_belongs_to_many :course_advance_types
end

#######
class Courses < ActiveRecord::Base
  has_one :course_advance_type
  has_many :students
end

Ideally I want a small form that allows a selection of advance type (academic, athletic) that will allow me to add students below it. Each student would be recorded in the course_advance_types_students table that is created for the HABTM association.

Something like this:

<form>
  <select>
    <option>academic</option>
    <option>athletic</option>
  </select>
  <div id="students">
     <div>Student ID: <input type="text" /></div>
     <div>Student ID: <input type="text" /></div>
     <!-- This link would dynamically add another name field -->
     <div><a href="[code]">Add Student</a></div>
  </div>
  <input type="submit>
</form>

What is the best way to accomplish this? I thought about using accepts_nested_attributes_for, but I don't know if that works because I don't want to set attributes for students, I want the student ID to be saved with the course_advance_type_id in the course_advance_types_students table so that I can pull a report of Courses that have advance students with the list of the advance type and the list of students.

If I need to clarify something or rethink my approach, please tell me.

Thank you.

Check out formtastic: https://github.com/justinfrench/formtastic

Much easier way to put a form together for a has_many/habtm relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM