Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'


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

I had to do this for a Mongoid object that had aliased fields.


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.


if very simplified

for Model columns < attributes < methods

for record columns = attributes < methods

Model.columns <> Model.record.columns/attributes

column

Checking the existence of a column for a model Foo.column_names.include? 'column_name'

Does the column exist for the record? foo.has_attribute?('column_name')

attribute

Checking the existence of a attribute for a model Foo.attribute_method?(:attribute_name)

Does the attribute exist for the record? foo.has_attribute?(:attribute_name)

method

Checking the existence of a method for a class Foo.method_defined?(:method_name)

Does the method exist for the instance? foo.respond_to?(:method_name)