ruby-on-rails - 有没有一种方法可以将 rails 中的值设置为 nil 并保存?

标签 ruby-on-rails ruby activerecord

我想到的是我可以说的话:

e = Foo.new
e.bar = "hello"
e.save
e.reload
e.bar.nil!
e.reload
e.bar.nil?  => true

有点像#touch,但设置为零并保存。

编辑

非常抱歉,伙计们。我的意思是:

e = Foo.new
e.bar = "hello"
e.save
e.reload
e.bar.nil!
e.reload
e.bar.nil?  => true

最佳答案

也许是这样的:

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) 清空评论的标题。

关于ruby-on-rails - 有没有一种方法可以将 rails 中的值设置为 nil 并保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46326738/

相关文章:

ruby-on-rails - 用于将字符串更改为整数的 Rails 迁移

sql - Rails/Rails3 SQL 查询, "LIKE"不能正确处理日期时间?

ruby-on-rails - 如何将Rails模型记录与代码关联?

ruby-on-rails - 设计:注册失败时重定向?

javascript - Ruby on Rails - 创建时部分不渲染链接

sql - rails/SQL : Find parents that have no child or have all children with a condition

ruby-on-rails-3 - 神秘的 SELECT COUNT(*) 出现在我的 Controller 中,用于 has_many 关系

ruby-on-rails - Rails check_box_tag 设置为默认值

ruby-on-rails - 在 ActiveModel 对象上,如何检查唯一性?

ruby - Textmate cucumber 包问题 - 'Run Feature' 产生错误