[英]rails before_save callback does not trigger
在我的Rails应用程序中,我想先检查通过表单发送的金额,然后再将其保存到数据库中。 如果数量太大,我想将布尔值“ confirmed”设置为false。 否则,其证实与成立。
我在模型中输入了以下内容:
# if amount is too big, set to unconfirmed
before_save do
if self.amount > 9999
self.confirmed = false
else
self.confirmed = true
end
end
控制器动作(脚手架):
def create
@statement = Statement.new(statement_params)
respond_to do |format|
if @statement.save
format.html { redirect_to thankyou_path, notice: 'Successfully created.' }
format.json { render action: 'show', status: :created, location: @statement }
else
format.html { render action: 'new' }
format.json { render json: @statement.errors, status: :unprocessable_entity }
end
end
end
测试结果如下:-如果数量<9999,则保存表格,一切正常。 -如果金额> 9999,则不会保存该表格。 它只是停留在同一页面上,没有任何反应。 除了没有将数据输入数据库之外,没有错误消息,在日志中也看不到任何内容。
我做错了什么?
这是因为,如果amount
大于9999,则从块返回的值为false
(从self.confirmed = false
行)-并且如果传递到before_save
块(或方法)返回false
,则ActiveRecord会停止保存记录。 因此,简单的解决方案是添加将返回的true
:
before_save do
if self.amount > 9999
self.confirmed = false
else
self.confirmed = true
end
true
end
相关文档供参考:
如果before_ *回调返回false,则所有更高版本的回调和关联的操作都将被取消。 如果after_ *回调返回false,则所有以后的回调都将被取消。 回调通常按照定义的顺序运行,但定义为模型上方法的回调除外,这些回调称为last。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.