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??

3
  • This might be helpful. It worked for me in a similar situation. Commented Mar 27, 2013 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. Commented Mar 27, 2013 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) Commented Mar 27, 2013 at 18:34

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.