2

I have two models on rails. The first is the patient model

class Patient

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

end

The second model holds extra info for female patients

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

Note: I didn't create the db schema and i can't change it.

So my question is: how can i reject the female object from being saved in the db by checking the :sex attribute in the patient object?

I tried

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

but it didn't work. ( sex is an integer and gets 0 for Male and 1 for Female )

Any thoughts??

Michael
  • 45
  • 7
  • [This](http://stackoverflow.com/a/5049311/382982) might be helpful. It worked for me in a similar situation. – pdoherty926 Mar 27 '13 at 17:11
  • I tried :before_add => :evaluate_sex and in my patient class i put `def evaluate_sex(female) if female.patient.sex == 0 return true else return false end end` But it didn't work. – Michael Mar 27 '13 at 17:51
  • Solved!!! I added an after_save callback which calls the check_sex functions that destroys the saved female record from the db if its parent object has sex filed set to Male ( if self.patient.sex ==0 self.destroy) – Michael Mar 27 '13 at 18:34

1 Answers1

3

I know this is old, but I just came across the same problem. You can use reject_if and pass a symbol in your patient model.

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
ltrainpr
  • 3,115
  • 3
  • 29
  • 40