views:

48

answers:

1

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?

+6  A: 

At the class level you can do: Number.column_names.include? attr_name where attr_name is the string name of your attribute. In this case it would be one.

If you have an instance, you can do: number.attributes.has_key? attr_name.

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