1
我想单击一个按钮上的动作,导致资源添加到连接表中。有几种方法可以在控制台中执行此操作,但我不能在我的生活中弄清楚如何在控制台之外实现此操作。Rails活动记录和嵌套资源
下面是模仿我目前的模型的例子:
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相关联的新行)。
一直试图弄清楚,但由于某种原因没有取得进展。先谢谢你!