如何检查模型是否具有某个列/属性?

我有一个方法,它需要遍历散列并检查模型表中是否存在每个键,否则它将删除键/值。

比如说

number_hash = { :one => "one", :two => "two" }

而 Number 表只有一个: 一列,因此: 两个将被删除。

如何检查模型是否有属性?

104193 次浏览

上课用的

使用 Class.column_names.include? attr_name,其中 attr_name是属性的字符串名称。

在这种情况下: Number.column_names.include? 'one'

举个例子

使用 record.has_attribute?(:attr_name)record.has_attribute?('attr_name')(Rails 3.2 +)或 record.attributes.has_key? attr_name

在这种情况下: number.has_attribute?(:one)number.has_attribute?('one')number.attributes.has_key? 'one'

如果还需要检查别名,可以使用 Number.method_defined? attr_namenumber.class.method_defined? attr_name

我必须为一个具有别名字段的 Mongoid 对象执行此操作。

在实例对象中,还可以使用 defined? instance.attributeinstance.respond_to? :attribute
这些是检查模型属性或任何方法的更通用的解决方案。

如果非常简单的话

对于 Model column < properties < method

对于 record column = properties < method

Column < > Model.record.column/properties

专栏

检查模型的列是否存在 Foo.column_names.include? 'column_name'

该列是否存在用于记录? foo.has_attribute?('column_name')

属性

检查模型的属性是否存在 Foo.attribute_method?(:attribute_name)

记录的属性是否存在? foo.has_attribute?(:attribute_name)

方法

检查类的方法是否存在 Foo.method_defined?(:method_name)

实例的方法是否存在? foo.respond_to?(:method_name)