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.

for example

number_hash = { :one => "one", :two => "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?


Solution 1:

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'

Solution 2:

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.

Solution 3:

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.