问题
I have a model called RsvpRegistrations with
belongs_to :rsvp
I need to use values from the parent 'rsvp' object in my validations such as
validates_presence_of :phone if self.rsvp.phone
(Rsvp.phone is boolean)
But this doesn't work. The error I get is undefined method `rsvp'. How can I access the parent object and its values?
Once I get it working, I have other similar validations to run, so I'm thinking I need to grab the parent 'rsvp' one time and then reference it in my other validations.
Thanks in advance.
回答1:
validates_presence_of :phone, :if => Proc.new { |obj| obj.rsvp.phone? }
More options here
回答2:
If you have multiple validations that all reference RSVP, it may be more efficient to create a custom validation method:
# app/models/rsvp_registration.rb
def RsvpRegistration
def validate
rsvp = self.rsvp
errors.add(:rsvp, 'Phone is missing') unless rsvp.phone?
errors.add(:rsvp, 'Other messages') if condition
end
end
来源:https://stackoverflow.com/questions/6671795/get-parent-values-in-child-model