How to check if a model has a certain column/attribute?


For a class

Use Class.column_names.include? attr_name where attr_name is the string name of your attribute.

In this case: 
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.

In this case: 
number.has_attribute?(:one) or number.has_attribute?('one') or number.attributes.has_key? 'one'


For bonus points use 
Hash#select: number_hash.select { |key, value| Number.column_names.include? key }

If you need to check for aliases as well, you can use 
Number.method_defined? attr_name or number.class.method_defined? attr_name.

In your instance object, you could use also defined? instance.attribute or instance.respond_to? :attribute.
 These are more generic solution to check a model attribute or any method as well.
Please keep in mind: 
instance.respond_to?(:attribute) == false ; instance.attribute ; instance.respond_to?(:attribute) == true 

阅读量: 585
发布于:
修改于: