如何从一个模型验证另一个模型中一个字段的存在

时间:2012-11-02 08:18:05

标签: ruby-on-rails ruby

我有一个模型PunchingRequest和一个模型PunchingInformation,在PunchingInformation中我有两个字段,punch_in_time和punch_out_time。当且仅当punch_in_time或punch_out_time中的至少一个包含值时,我想在冲压请求表中插入记录。我有一个包含与PunchingRequest和PunchingInformation相关的字段的表单。我如何强制进行此验证?

2 个答案:

答案 0 :(得分:1)

使用这样的自定义验证:

validate :presence_of_punch_in_time_or_punch_out_time

def presence_of_punch_in_time_or_punch_out_time
  # Use PunchingInformation.where(...)
  # or this.your_object_relation_with_punching_information
  # to get the other model row.
  errors[:base] << "Wrong punching information" unless row.punch_in_time || row.punch_out_time
end

答案 1 :(得分:0)

您可以在PunchingRequest模型中编写自定义验证,例如

validate :validate_punching_information

def validate_punching_information
  errors[:base] << 'Either punch in or punch out should be present' if self.punching_information.punch_in_time.nil? && self.punching_information.punch_out_time.nil?
end

我假设PunchingRequest和PunchingInformation是一对一相关的

相关问题