开发者

get parent values in child model

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.


validates_presence_of :phone, :if => Proc.new { |obj| obj.rsvp.phone? }

More options here


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜