RE: A Describe Method / Pull list of Fields

Rilindo, the class method “columns” called on an ActiveRecord class is what you want. Let’s say you have a table called “books” with corresponding model Book. Then:

Book.columns will return an array of column objects of the columns in the table. Not so useful for a select list.

Book.columns.collect{|x| x.name} will return an array of just the column names. But this will contain the “id” column and maybe other foreign keys you don’t want in a select list. Therefore:

Book.columns.collect{|x| x.name}.reject{|x| x == ‘id’ || x.match(/_id\Z/)} might be closer to what you want,

Cheers, --Kip

Topic: A Describe Method / Pull list of Fields

Rilindo Foster rilindo@gmail.com Dec 17 11:17PM -0500

Is there a method that can either run a describe on the table or pull a list of fields from a table? The rationale is that I am looking for a while to automatically populate a drop down list so that I can execute a search based on the field name submitted from the form. I can, of course, populate it manually, but with 8+ models, it gets old fast.

Is this the way to do it, through? Or should I try something like Sphinx for these type of searches (which I am thinking of using anyway).

  • Rilindo

There is also the ActiveRecord::Base method column_names.

Which essentially returns the same thing as Book.column_names.collect
(&:name)