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

Viewed 102258

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?

4 Answers

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)

Related