Ruby-on-rails 如何检查模型是否具有特定的列/属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1710004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a model has a certain column/attribute?
提问by dMix
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.
我有一个方法需要遍历哈希并检查模型表中是否存在每个键,否则它将删除键/值。
for example
例如
number_hash = { :one => "one", :two => "two" }
and the Number table only has a :one column so :two will be deleted.
并且 Number 表只有一个 :one 列,因此 :two 将被删除。
How do I check if a model has an attribute or not?
如何检查模型是否具有属性?
回答by Andy Stewart
For a class
对于一个班
Use Class.column_names.include? attr_namewhere attr_nameis the string name of your attribute.
使用Class.column_names.include? attr_namewhereattr_name是属性的字符串名称。
In this case: Number.column_names.include? 'one'
在这种情况下: Number.column_names.include? 'one'
For an instance
例如
Use record.has_attribute?(:attr_name)or record.has_attribute?('attr_name')(Rails 3.2+) or record.attributes.has_key? attr_name.
使用record.has_attribute?(:attr_name)或record.has_attribute?('attr_name')(Rails 3.2+)或record.attributes.has_key? attr_name。
In this case: number.has_attribute?(:one)or number.has_attribute?('one')or number.attributes.has_key? 'one'
在这种情况下:number.has_attribute?(:one)或number.has_attribute?('one')或number.attributes.has_key? 'one'
回答by Nick
If you need to check for aliases as well, you can use Number.method_defined? attr_nameor number.class.method_defined? attr_name.
如果您还需要检查别名,您可以使用Number.method_defined? attr_name或number.class.method_defined? attr_name。
I had to do this for a Mongoid object that had aliased fields.
我必须为具有别名字段的 Mongoid 对象执行此操作。
回答by Alter Lagos
In your instance object, you could use also defined? instance.attributeor instance.respond_to? :attribute.
These are more generic solution to check a model attribute or any method as well.
在您的实例对象中,您也可以使用defined? instance.attribute或instance.respond_to? :attribute。
这些是检查模型属性或任何方法的更通用的解决方案。

