如果同一模型的另一个属性在 rails 中更改,则自动删除模型属性
Automatically remove a model attribute if another attribute of same model changed in rails
所以我想在同一模型的特定其他属性更改时自动删除模型属性。
我有一个名为 profile
的 rails 模型,它有一个 picture
属性,其中包含我们图像存储中图像的 URL。此外,该模型还有一个 crop_data
属性,其中包含将图像的哪一部分呈现给用户的信息,该属性可由用户设置,默认为 profile.crop_data? # => false
如果 profile.picture
属性更改或得到 removed/reset
profile.crop_data? # should return false
并在数据库中重置为默认值。
实现此目的最简洁的方法是什么?不幸的是我们仍然 运行 Rails 3.2.21
.
您可以使用保存前回调:
class Profile
before_save :check_crop_data
def check_crop_data
if self.changed_attributes.has_key?(:profile_picture)
self.crop_data = true
elsif picture.nil?
self.crop_data = false
end
end
end
所以我想在同一模型的特定其他属性更改时自动删除模型属性。
我有一个名为 profile
的 rails 模型,它有一个 picture
属性,其中包含我们图像存储中图像的 URL。此外,该模型还有一个 crop_data
属性,其中包含将图像的哪一部分呈现给用户的信息,该属性可由用户设置,默认为 profile.crop_data? # => false
如果 profile.picture
属性更改或得到 removed/reset
profile.crop_data? # should return false
并在数据库中重置为默认值。
实现此目的最简洁的方法是什么?不幸的是我们仍然 运行 Rails 3.2.21
.
您可以使用保存前回调:
class Profile
before_save :check_crop_data
def check_crop_data
if self.changed_attributes.has_key?(:profile_picture)
self.crop_data = true
elsif picture.nil?
self.crop_data = false
end
end
end