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

时间:2021-09-09 19:35:57

I have one model PunchingRequest and one model PunchingInformation, In PunchingInformation i have two fields, punch_in_time and punch_out_time. I want to insert record in punching requests table if and only if atleast one out of punch_in_time or punch_out_time contains a value. I have a form containing fields related to both PunchingRequest and PunchingInformation. How can I impose this validation?

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

2 个解决方案

#1


1  

Use a custom validation like this:

使用这样的自定义验证:

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

#2


0  

you can write custom validation in the PunchingRequest model like

你可以在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

I am assuming that PunchingRequest and PunchingInformation are one to one related

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

#1


1  

Use a custom validation like this:

使用这样的自定义验证:

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

#2


0  

you can write custom validation in the PunchingRequest model like

你可以在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

I am assuming that PunchingRequest and PunchingInformation are one to one related

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