2014-06-17 35 views
1

我有兩種不同的模型:患者和樣本。一個病人可以有幾個樣本,一個樣本屬於一個病人。保存後更新不同的模型屬性

這裏是簡化了兩種模式(只有我需要爲這個問題的信息...):

class Sample < ActiveRecord::Base 
attr_accessible :dateOfSample, :patient_attributes, :infantBreastFeedingAtThisTime, :typeBreastFeedingAtThisTime, :idadeDesmameAtThisTime 

belongs_to :patient 
accepts_nested_attributes_for :patient 
end 

和病人模型:

class Patient < ActiveRecord::Base 

    attr_accessible :date_of_birth, :infant_name, :infantBreastFeeding, :typeBreastFeeding,:idadeDesmame 
    has_many :samples 
end 

我想要做的是什麼,每次創建或更新樣本時,如果「dateOfSample」是最後一個可用樣本,我想用最後一個特定樣本屬性(:infantBreastFeedingAtThisTime,:typeBreastFeedingAtThisTime,:idadeDesmameAtThisTime更新患者屬性(:infantBreastFeeding,:typeBreastFeeding,:idadeDesmame) )

如何在示例模型中執行此操作?使用after_save?我試過但不能通過病人的屬性,所以它不承認病人...這應該是一個簡單的錯誤,我正在製作,仍軌道noob :)

謝謝!

更新:

我有一個插入/更新示例的表單。在該表單中,我有一個部分用於病人字段(名稱和日期出生)。對不起,不張貼表格,但它太大了...

+0

樣本是否會一直添加爲患者表單的嵌套屬性? –

+0

不,我有一個帶有「patient_id」的樣本表格,我還顯示了一些其他患者屬性。但是,是的,我創建或更新了一個樣本,它必須具有患者屬性 – lbramos

+0

您對我的問題的回答很混亂,請問您是否可以將您所談論的表格添加到您的問題中? –

回答

1

你可以通過幾種不同的方式去解決這個問題。首先,可以按如下方式嘗試一個after_save方法:

class Sample < ActiveRecord::Base 
    after_save :update_patient 

    def update_patient 
    if self.class.where(patient: self.patient).maximum(:dateOfSample) == self.dateOfSample 
     self.patient.update_attributes(infantBreastFeeding: infantBreastFeedingAtThisTime, 
            typeBreastFeeding: typeBreastFeedingAtThisTime, 
            idadeDesmame: idadeDesmameAtThisTime) 
    end 
    end 
end 

其次,你可以在你的控制器設置的屬性上創建或更新。

class SamplesController < ApplicationController 
    # call this in both your create and update methods before you save 
    def assign_sample_attributes_to_product   
    if Sample.where(patient: @sample.patient).maximum(:dateOfSample) < @sample.dateOfSample) 
     @sample.assign_attributes(infantBreastFeeding: @sample.infantBreastFeedingAtThisTime, 
           typeBreastFeeding: @sample.typeBreastFeedingAtThisTime, 
           idadeDesmame: @sample.idadeDesmameAtThisTime) 
    end 
    end 
end 

希望這可以幫助你!

+0

我試過選項1,我得到:ArgumentError:錯誤的參數數量(1代表0),與「max」有關 – lbramos

+0

哎呀抱歉!它應該是「最大」,而不是「最大」。我總是把這些混在一起。我已經更新了我的答案。 –

+0

謝謝,它的工作原理!我正在尋找一個替代品,但你打敗了我:)我愛你的解決方案,代碼比我想寫的更清潔和優雅! – lbramos