将 ActiveRecord 对象的所有属性(id、created_at、updated_at 除外)设置为 nil 的最简单方法是什么? [英] What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil?

查看:36
本文介绍了将 ActiveRecord 对象的所有属性(id、created_at、updated_at 除外)设置为 nil 的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 ActiveRecord 对象的所有属性(id、created_at、updated_at 除外)设置为 nil 的最简单方法是什么?

What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil?

推荐答案

模型上有一个名为 attribute_names 的数组,它确实包含了所有的属性,所以使用 reject 来过滤属性:

There's an array called attribute_names on the model, which does include all attributes, so use reject to filter attributes:

class Model < AR::Base
  def nilify_attributes!(except = nil)
    except ||= %w{id created_at updated_at}
    attribute_names.reject { |attr| except.include?(attr) }.each { |attr| self[attr] = nil }
  end
end

参见 http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-attribute_names

这篇关于将 ActiveRecord 对象的所有属性(id、created_at、updated_at 除外)设置为 nil 的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆