Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails -- get the names of all a table's columns of a certain data type? (#column_names for just float cols, for ex.)

In rails, we can do this:

TableName.column_names

and get an array of all a table's column names as strings.

Is there any way I could, in some streamlined, ruby-like fashion, get all the column_names of a table that are numerical? Or all that are floats? Or strings, etc?

Right now, I'm simply locating all the non-numerical column names of the table I'm working with and subtracting them as an array from the list of all the table's column names like so:

cols = TableName.column_names - ["name", "created_at", "location", ... ]

There are over a hundred numerical columns so this is my best solution right now, but it feels like a hack

like image 774
boulder_ruby Avatar asked Dec 05 '25 03:12

boulder_ruby


1 Answers

This will do the trick:

ModelClass.columns.select{ |c| c.type == :integer }.map(&:name)

The column objects returned by #columns contain most of the information present in your schema, including what type they are, whether they are nullable or have a default value, etc.

Note that this list will include, for instance, the id column and any xyz_id columns that are used to reference associations. You can filter out id by checking #primary, but the xyz_id columns aren't "special" from the schema's point of view, so you might have to blacklist them manually. (If accidentally including unwanted columns in your list would cause bad things to happen, a safer approach might be to forget about schema introspection and simply maintain a whitelist of columns you want.)

like image 115
DigitalCora Avatar answered Dec 06 '25 18:12

DigitalCora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!