gpt4 book ai didi

ruby-on-rails - 调用 before_save 操作时记录不保存

转载 作者:行者123 更新时间:2023-12-01 08:25:49 24 4
gpt4 key购买 nike

无法弄清楚。不知道为什么没有保存记录。方法被正确调用,所有字段都存在,逻辑正确。这是我的模型代码:

class Mine < ActiveRecord::Base
belongs_to :shop
validates :merchant_id, presence: true
validates :auth_token, presence: true
before_save :assign_three_speed


private

def assign_three_speed
if CreateFulfillmentService::NON_US_MARKETPLACES.include?
(self.marketplace)
self.three_speed = false
else
self.three_speed = true
end
end
end

好吧,这太疯狂了..我放入了一些记录器,现在它确实保存了??这是我的代码:

  def assign_three_speed
Rails.logger.info "What is self?? #{self.inspect}"
if CreateFulfillmentService::NON_US_MARKETPLACES.include?
(self.marketplace)
self.three_speed = false
else
self.three_speed = true
end
Rails.logger.info "Now what is self?? #{self.inspect}"
end

最佳答案

在 5.0.0 之前的 Rails 版本中,从回调方法返回 false 将取消保存。来自 Rails 4.2.7 文档:

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

设置self.three_speed = false时,是方法中运行的最后一条语句,所以false是assign_three_speed方法的返回值。这就是为什么将记录器添加到最后一行修复它的原因。让该方法返回一些其他值。

如果您不想取消回调,则在最后一行返回 true:

def assign_three_speed
if CreateFulfillmentService::NON_US_MARKETPLACES.include(self.marketplace)
self.three_speed = false
else
self.three_speed = true
end

true
end

关于ruby-on-rails - 调用 before_save 操作时记录不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39540175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com