2013-03-27 19 views
2

我在rails上有兩個模型。 首先是患者模型Rails的accep_nested_attributes_for。使用reject_if通過使用父對象的屬性來拒絕對象

class Patient 

attr_accessible :name, :age, :sex, :female_attributes 
has_one :female, dependent => :destroy 
accepts_nested_attributes_for :female, allow_destroy => true 

end 

第二種模式適用於女性患者

class Female 
belongs_to :patient 
attr_accessible :patiend_id, :pregrnant_now: :childbirths 
end 

注意額外的信息:我沒有創建數據庫架構,我無法改變它。

所以我的問題是:我怎麼能拒絕來自通過檢查被保存在數據庫中的女性對象:在病人對象的性別屬性?

我試圖

reject_if => lambda { |a| a['sex'].to_i == 0) } 

,但沒有奏效。 (性別是整數和女性得0爲雄性和1)

任何想法??

+0

[This](http://stackoverflow.com/a/5049311/382982)可能會有所幫助。它在類似的情況下爲我工作。 – pdoherty926 2013-03-27 17:11:09

+0

我想:before_add =>:evaluate_sex和我的病人類我把 '高清evaluate_sex(女) 如果female.patient.sex == 0 還真 否則 返回false 結束 end' 但沒有工作。 – Michael 2013-03-27 17:51:29

+0

解決!我添加了一個after_save回調,它調用check_sex函數,如果其父對象的性別字段設置爲Male,則會從db中銷燬保存的女性記錄(如果self.patient.sex == 0 self.destroy) – Michael 2013-03-27 18:34:01

回答

3

我知道這是老了,但我只是碰到了同樣的問題來了。您可以使用reject_if並在患者模型中傳遞符號。

class Patient 

    attr_accessible :name, :age, :sex, :female_attributes 
    has_one :female, dependent => :destroy 
    accepts_nested_attributes_for :female, 
    reject_if: :female_patient?, 
    allow_destroy => true 

    def female_patient? 
    self.sex.to_i == 1 
    end 
end 
相關問題