Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: get all field for an object coming from the database

Let's say I have an Foo ActiveRecord model with fields foo_id, foo_name and foo_description.

After doing something like

@foo = Foo.find(1)

Is there any method "model_fields" such that: @foo.model_fields() would return the array:

["foo_id", "foo_name", "foo_description"] ?

Thanks for the help.

like image 428
Nicolas M. Avatar asked Oct 25 '10 00:10

Nicolas M.


1 Answers

There is an attributes method that give a hash of field and values. So you could use

@foo.attributes.keys

To get an array of the fields on the model.

There's also a Foo.column_names class method that gives you the same information without having to look up a record first.

Documentation for:
ActiveRecord::Base.column_names
ActiveRecord::Base#attributes

like image 68
Emily Avatar answered Oct 19 '22 10:10

Emily