activerecord - 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, can this:

tablename.column_names 

and array of table's column names strings.

is there way could, in streamlined, ruby-like fashion, column_names of table numerical? or floats? or strings, etc?

right now, i'm locating non-numerical column names of table i'm working , subtracting them array list of table's column names so:

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

there on hundred numerical columns best solution right now, feels hack

this trick:

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

the column objects returned #columns contain of information present in schema, including type are, whether nullable or have default value, etc.

note list include, instance, id column , xyz_id columns used reference associations. can filter out id checking #primary, xyz_id columns aren't "special" schema's point of view, might have blacklist them manually. (if accidentally including unwanted columns in list cause bad things happen, safer approach might forget schema introspection , maintain whitelist of columns want.)


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -