16

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.

ksugiarto
  • 940
  • 1
  • 17
  • 40
Nicolas M.
  • 789
  • 1
  • 13
  • 23

1 Answers1

40

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

Emily
  • 17,813
  • 3
  • 43
  • 47
  • Thanks Emily for the quick answer! I am using .attributes= all the time. Not sure why I didn't think about that... – Nicolas M. Oct 25 '10 at 00:45
  • 1
    And if you need to loop through attributes and values, it's simple to do so with a block: `@foo.attributes.each do |k,v|` – Steph Rose Jun 06 '12 at 14:27
  • Sometimes I need the column names as symbols, `Model.column_names.map(&:to_sym)` to the rescue. – Epigene Jan 05 '17 at 13:13