如何检查模型是否具有特定的列/属性? [英] How to check if a model has a certain column/attribute?
问题描述
我有一个方法需要遍历哈希并检查模型表中是否存在每个键,否则将删除键/值.
I have a method that needs to loop through a hash and check if each key exists in a models table, otherwise it will delete the key/value.
例如
number_hash = { :one => "one", :two => "two" }
而 Number 表只有一个 :one 列,所以 :two 将被删除.
and the Number table only has a :one column so :two will be deleted.
如何检查模型是否具有属性?
How do I check if a model has an attribute or not?
推荐答案
对于一个班级
使用Class.column_names.include?attr_name
其中 attr_name
是您的属性的字符串名称.
Use Class.column_names.include? attr_name
where attr_name
is the string name of your attribute.
在这种情况下:Number.column_names.include?'一个'
举例
使用 record.has_attribute?(:attr_name)
或 record.has_attribute?('attr_name')
(Rails 3.2+) 或 record.attributes.has_key?attr_name
.
Use record.has_attribute?(:attr_name)
or record.has_attribute?('attr_name')
(Rails 3.2+) or record.attributes.has_key? attr_name
.
在这种情况下:number.has_attribute?(:one)
或 number.has_attribute?('one')
或 number.attributes.has_key?'一个'
In this case: number.has_attribute?(:one)
or number.has_attribute?('one')
or number.attributes.has_key? 'one'
这篇关于如何检查模型是否具有特定的列/属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!