我有一个自定义验证。我应该重写什么。 我想检查一下当日工人的唯一性。
这是我的代码:
class CrewWorker < ApplicationRecord
belongs_to :crew
belongs_to :worker
validate :uniq_worker_in_scope_of_day, if: -> obj { obj.new_record? && obj.crew.present? && obj.worker.present? }, on: :create
private
def uniq_worker_in_scope_of_day
assignment = crew.assignment #Assignment entity
crews_leader_ids = assignment.crews.map(&:leader_id) #[1,1]
active_worker_ids = assignment.worker_ids #[9,1]
workers = active_worker_ids - crews_leader_ids [9]
if workers.include?(worker.id) # workers = [9], worker.id = 1
errors.add(:base, 'has been already assigned at current day')
end
end
end
class Crew < ApplicationRecord
belongs_to :assignment, inverse_of: :crews
end
class Assignment < ApplicationRecord
belongs_to :company
has_many :crews, ->{ order(created_at: :asc) }, dependent: :destroy, inverse_of: :assignment
has_many :crew_workers, through: :crews, dependent: :destroy
has_many :workers, through: :crew_workers
has_many :assignment_items, through: :crews, dependent: :destroy
end
,但此验证有效2次。然后下一圈返回:
#first_lap:
workers = [9]
worker.id = 1
#second_lap:
workers = [9]
worker.id = 9
为什么在第二圈它返回9和9,而不是9和1。 注释中的p.s是调试器返回的内容。