【问题标题】:Rails: Data not getting saved with assign_attributes in before saveRails:保存前未使用 assign_attributes 保存数据
【发布时间】:2020-06-23 15:56:29
【问题描述】:

我正在 before_save 中进行如下更新:

has_many :things

before_save :set_things

def set_things
  things = all_things.map do |t|
    t.assign_attributes(attrs) 
    t
  end
  self.things = things
end

当我将对象保存为 t.save! 时,对象具有更新的属性,但一旦重新加载它就会恢复到旧值,因此更新不会持续。如果我使用 t.update_attributes 它工作正常,但 assign_attributes 不应该在保存时持续存在吗?为什么它不起作用?

【问题讨论】:

  • 您使用的是什么版本的导轨?在 5 之前的版本中,从回调中返回非真实值可以取消当前正在执行的操作(例如保存)。如果您运行的版本低于 5,请尝试在回调底部添加 true
  • Assign_attributes 它应该在保存后持续存在。这个回调内部发生了一些事情。您是否曾经尝试在回调中放置一个常量值只是为了查看它是否已保存?比如删除所有代码并只放self.things = [Thing.new()]

标签: ruby-on-rails ruby update-attributes before-save


【解决方案1】:

这已经解决了。因为,我正在更新现有记录,所以 assign_attribute 没有更新属性。只有新记录会根据这个更新: Rails: Why “collection=” doesn't update records with existing id?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 2014-12-07
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多