【发布时间】:2017-09-27 12:39:45
【问题描述】:
在OpenProject 应用程序中,我们有两个模型:
class CustomField < ActiveRecord::Base
has_many :custom_options, -> { order(position: :asc) }, dependent: :delete_all
accepts_nested_attributes_for :custom_options
...
end
class CustomOption < ActiveRecord::Base
belongs_to :custom_field, touch: true
...
end
然后在custom field controller我们通过批量赋值修改自定义字段的选项并保存记录:
@custom_field.attributes = get_custom_field_params
if @custom_field.save
...
因为touch: true 是在CustomOption 中的custom_field 关联上配置的,所以我预计自定义字段的updated_at 属性此时会更新,但是这不会发生。该日志没有显示任何类似于UPDATE custom_fields SET update_at = .... 的SQL 请求。对自定义选项本身的更改,无论是添加自定义选项还是修改自定义选项,都会正确保留。
调试显示:
- 使用
custom_field.custom_options.build和后续custom_field.save时出现相同的错误行为 - 使用
custom_field.custom_options.create时的期望行为 - 使用
CustomOption.create custom_field: x时的期望行为 - 使用
custom_field.custom_option[x].destroy时的期望行为
我知道我可以通过定义after_save 回调来解决这个问题,但是这种行为真的让我很恼火,因为它是出乎意料的。
上述行为是否需要并记录在案?如果是这样,我在哪里可以找到这些信息?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-5 rails-activerecord