为 HABTM 协会创建表格
这就是我想要实现的目标。我有学生注册的课程。我想跟踪那个班的先进学生。我建立了另一个模型,称为 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
理想情况下,我想要一个小表格,允许选择高级类型(学术、运动),这样我就可以在其下面添加学生。每个学生都将记录在为 HABTM 关联创建的 course_advance_types_students 表中。
像这样的事情:
<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>
完成此任务的最佳方法是什么?我考虑过使用accepts_nested_attributes_for,但我不知道这是否有效,因为我不想为学生设置属性,我希望学生ID与course_advance_types_students表中的course_advance_type_id一起保存,以便我可以提取报告具有高级学生的课程以及高级类型列表和学生列表。
如果我需要澄清某些事情或重新考虑我的方法,请告诉我。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看 formtastic: https://github.com/justinfrench/formtastic
将表单组合在一起的更简单方法对于 has_many/habtm 关系。
Check out formtastic: https://github.com/justinfrench/formtastic
Much easier way to put a form together for a has_many/habtm relationship.