2014-02-20 95 views
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相關聯的新行)。

一直試圖弄清楚,但由於某種原因沒有取得進展。先謝謝你!

回答

1

好了,首先,在你看來,你應該有一個JavaScript/DOM事件爲每所學校:

onclick(window.location.href = "<%= path_to_add_school_to_students(student,school) %>") 

所以你有你的點擊。

在你的控制器

student=Student.find(params[:student]) 
if student.schools.find(params[:school]).nil? # if school not already assigned 
    student.reports.create(:school_id => params[:school]) 
end