【发布时间】:2014-02-21 06:14:29
【问题描述】:
我希望对按钮进行单击操作以将资源添加到连接表中。在控制台中有几种方法可以做到这一点,但我一生都无法弄清楚如何在控制台之外实现这一点。
这是一个模仿我当前模型的示例:
class Student < ActiveRecord::Base
has_many :reports
has_many :schools, through: :reports
end
class School < ActiveRecord::Base
has_many :reports
has_many :students, through: :reports
accepts_nested_attributes_for :reports
end
class Report < ActiveRecord::Base
belongs_to :student
belongs_to :school
accepts_nested_attributes_for :student
accepts_nested_attributes_for :school
validates :student_id, presence: true
validates :school_id, presence: true
end
这个方法返回属于一个学生的所有成绩单(学生已经存在于 我的数据库):
@student.reports
这个方法返回一个学生就读的所有学校:
@student.schools
我可以通过这样做将现有学校添加/关联到学生:
@school = School.find(params[:id])
if student.present?
@student = Student.find(params[:id])
@student.schools << @school
请注意,将一份报告与许多学生关联是有意的。我现在的问题是如何让学生只需单击特定学校就可以将学校添加到他们的报告中?我的报告表(基本上是一个连接表)应该在这个 click_action 发生/发生时自动更新(这是一个将特定 student_id 与特定学校 id 相关联的新行)。
一直试图弄清楚,但由于某种原因没有取得进展。提前谢谢!
【问题讨论】:
标签: ruby-on-rails activerecord