0

我在其中學生可以申請公佈僱主項目Rails應用程序。我擁有這樣一個學生has_many項目,以及一個項目belongs_to學生。問題在於,在選擇一個學生之前,項目可能會存在很長時間。我的意思是,除非僱主在視圖中按下租用按鈕,否則項目的student_id爲零。一旦僱主按下「僱用」按鈕,我正在嘗試將項目的student_id設置給被聘用的學生。出於某種原因,我不能這樣做。這裏是項目模型:的Rails belongs_to的關係,如果滿足一定條件

class Project < ActiveRecord::Base 
     belongs_to :student 
     belongs_to :employer 
     has_many :relationships 

    def change_it 
     self.student_id = self.relationships.where(:state => :active).first.student_id 
     self.relationships.each do |relationship| 
      if relationship.state != :active 
      relationship.deny_applicants 
      end 
     end 
    end 
end 

當我點擊按鈕租用,它需要我到下一個頁面爲正常,但是當我在控制檯檢查項目的student_id數據,它仍然是零。

我該如何解決這個問題?謝謝。

+0

一個想法的人?我一直在工作幾個小時 - 仍然無法實現它的工作。 – Philip7899

回答

0

我認爲你要爲大家介紹的附加模型來捕捉學生與項目之間的關係。也許重申這個問題將有助於澄清這一點。

  • 教授可以在任何時候創建一個項目
  • 學生可以隨時申請項目已被張貼後
  • 教授必須批准一個學生分配到項目

第一點建議項目屬於教授(不是學生)。從第二點和第三點我往往會說,一個學生有一個分配給項目和分配可能「應用」,「批准」和「拒絕」狀態。考慮到這一點我可能會這樣模型,可以(與state_machine寶石):

class Student < ARec 
    has_many :assignments 
    has_many :approved_assignments, class_name: 'Assignment', conditions: { state: 'approved' } 
end 

class Project < ARec 
    has_many :assignments 
    has_one :approved_assignment, class_name: 'Assignment', conditions: { state: 'approved' } 
end 

class Assignment < ARec 
    belongs_to :student 
    belongs_to :project 

    state_machine :state, initial: :applied do 
    state: :approved 
    state: :declined 

    event :approve do 
     transition all => :approved 
    end 

    event :decline do 
     transition all => :declined 
    end 
    end 
end 
+0

我實際上已經在項目中使用了狀態機gem。我想你打到了我想要做的事情,只是沒有增加的關係。我現在擁有的是一個項目最初處於狀態'發佈。當一個學生被錄用時,它會更改爲狀態'actual_job'。我想要的是當它更改爲狀態'actual_job'時,讓student_id與正確的學生關聯。任何想法如何做到這一點? – Philip7899

+0

對不起,我忽略了關係 - 它與我提議的作業基本相同。你如何調用Project#change_it? – AndyV

+0

我用這個:'after_transition:posting =>:actual_job,:do =>:change_it'。我知道它被調用,因爲deny_applicants的作品。 – Philip7899

0

你有關聯設置正確。

如果錯誤在項目#change_it發生,那麼我懷疑

self.relationships.where(:state => :active).first 

沒有返回的關係。

+0

我不明白這是怎麼回事。您的評論確實讓我重新思考這個問題,因此我使用更多信息更新了內容。 – Philip7899

+0

你不告訴我們,建立關係和分配student_id數據和PROJECT_ID的關係的代碼。您所描述的工作流程何時發生? –

0

我終於想通了。只需爲student_id設置一個新值就不會更新數據庫。我需要使用像這樣的update_attributes:

def change_it 
    self.update_attributes(student_id: self.relationships.where(:state => :active).first.student_id) 

    self.relationships.each do |relationship| 
     if relationship.state != :active 
     relationship.deny_applicants 
     end 
    end 
end