-
Following is a code snippet. after_save code_and_batch_level_must_uniq
def code_and_batch_level_must_uniq(saved_record : University)
code.value.try do |code_value|
batch_level.value.try do |batch_level_value|
if UniversityQuery.new.code(code_value).batch_level(batch_level_value).select_count > 1
self.code.add_error("编码和批次的组合, 必须唯一")
raise Avram::InvalidOperationError.new(self)
end
end
end
end What I need to ensure is that in the database, same Above code work, but will raise 500 if user insert new same code and batch_level record. So, how to get error message(as add_error in before_save) only instead raise 500 when use input error? Following situation i have tried:
before_save code_and_batch_level_must_uniq
def code_and_batch_level_must_uniq
code.value.try do |code_value|
batch_level.value.try do |batch_level_value|
query = UniversityQuery.new.code(code_value).batch_level(batch_level_value)
if query.select_count >= 1
if new_record?
self.code.add_error("编码和批次的组合, 必须唯一")
else
if query.first.id != id.value
self.code.add_error("编码和批次的组合, 必须唯一")
end
end
end
end
end So, i perfer use before_save to achieve this goal. Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I'm not completely clear on what the issue is, but when you use after_save code_and_batch_level_must_uniq
def code_and_batch_level_must_uniq(saved_record : University)
code.value.try do |code_value|
if not_unique_code
code.add_error("must be unique")
database.rollback # this line will un-save the university record
end
end
end |
Beta Was this translation helpful? Give feedback.
I'm not completely clear on what the issue is, but when you use
after_save
you are still inside of the initial database transaction. So you can calldatabase.rollback
which will un-do the original object save.