我想到的是我可以说的话:
e = Foo.new
e.bar = "hello"
e.save
e.reload
e.bar.nil!
e.reload
e.bar.nil? => true
#touch的种类,但设置为nil并保存。
修改
超级对不起的家伙。我的意思是:
e = Foo.new
e.bar = "hello"
e.save
e.reload
e.bar.nil!
e.reload
e.bar.nil? => true
答案 0 :(得分:0)
您无法将nil
保存到数据库中,而且,一旦将对象创建为特定类,您就永远无法更改它。它只能通过创建一个新对象来转换,就像这个假设nil!
那样的就地修饰符。
你最接近的是:
e = Foo.new
e.bar = "hello"
e.save
e.reload
e.delete!
e.reload
e.destroyed? # => true
f = Foo.find_by(id: e.id)
f.nil? # => true
答案 1 :(得分:0)
可能是这样的:
module ActiveRecord
class Base
def nil!(*names)
unless persisted?
raise ActiveRecordError, <<-MSG.squish
cannot nil on a new or destroyed record object. Consider using
persisted?, new_record?, or destroyed? before nilling
MSG
end
unless names.empty?
changes = {}
names.each do |column|
column = column.to_s
changes[column] = write_attribute(column, nil)
end
primary_key = self.class.primary_key
scope = self.class.unscoped.where(primary_key => _read_attribute(primary_key))
if locking_enabled?
locking_column = self.class.locking_column
scope = scope.where(locking_column => _read_attribute(locking_column))
changes[locking_column] = increment_lock
end
clear_attribute_changes(changes.keys)
result = scope.update_all(changes) == 1
if !result && locking_enabled?
raise ActiveRecord::StaleObjectError.new(self, "nil")
end
@_trigger_update_callback = result
result
else
true
end
end
end
end
将它放在初始化程序中,它会让你用Comment.last.nil!(:title)
清空评论的标题。