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

Ruby on-Rails

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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 - Ruby on-Rails

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 - Ruby on-Rails

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.

Solution 4 - Ruby on-Rails

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkushView Question on Stackoverflow
Solution 1 - Ruby on-RailsAndy StewartView Answer on Stackoverflow
Solution 2 - Ruby on-RailsNickView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAlter LagosView Answer on Stackoverflow
Solution 4 - Ruby on-RailsaskrynnikovView Answer on Stackoverflow