如何仅在更新某些属性时更新时间戳?
How to update a timestamp only when certain attributes are updated?
我需要一个时间戳列,它只在某些字段更新时更新,例如,如果产品名称更改,attributes_updated_at 字段应更新为 Time.now。我不希望在添加外键关联的情况下更新字段,或者如果 product.status
从 'pending'
更改为 'active'
。
有没有办法在模型中简单地定义它?
我认为您的问题是数据库问题,而不是 ruby 问题。
您可以使用例如数据库触发器(这是 mysql 代码)实现所需的行为。
CREATE TRIGGER trigger_product AFTER UPDATE ON product
FOR EACH ROW
BEGIN
IF (NEW.name <> OLD.name) or (NEW.category <> OLD.category)
THEN set NEW.updated_at = NOW();
END;
你可以试试
假设您有 Product
个模型
class Product < ActiveRecord::Base
belongs_to :user
before_save :stop_update_time_stamps
def stop_update_time_stamp
self.class.record_timestamps = false if self.status.changed? || self.user_id.changed?
end
end
我需要一个时间戳列,它只在某些字段更新时更新,例如,如果产品名称更改,attributes_updated_at 字段应更新为 Time.now。我不希望在添加外键关联的情况下更新字段,或者如果 product.status
从 'pending'
更改为 'active'
。
有没有办法在模型中简单地定义它?
我认为您的问题是数据库问题,而不是 ruby 问题。
您可以使用例如数据库触发器(这是 mysql 代码)实现所需的行为。
CREATE TRIGGER trigger_product AFTER UPDATE ON product
FOR EACH ROW
BEGIN
IF (NEW.name <> OLD.name) or (NEW.category <> OLD.category)
THEN set NEW.updated_at = NOW();
END;
你可以试试
假设您有 Product
个模型
class Product < ActiveRecord::Base
belongs_to :user
before_save :stop_update_time_stamps
def stop_update_time_stamp
self.class.record_timestamps = false if self.status.changed? || self.user_id.changed?
end
end