get parent values in child model

社会主义新天地 提交于 2019-12-24 10:01:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!