0

How do I get from a Ruby model all attributes or column_names which belong to a certain class (that is, which have a certain column type in the database)?

E.g.:
-Get all column_names belonging to class ActiveSupport::TimeWithZone from following Model having fields:
:id
:order_id String
:slot_id Integer
:delivery_date TimeWithZone
:packed_date TimeWithZone
:created_at TimeWithZone
:updated_at TimeWithZone

-Output:
['created_at','updated_at','delivery_date','packed_date']
kattybilly
  • 117
  • 1
  • 8
  • Possible duplicate of [Fastest/One-liner way to list attr\_accessors in Ruby?](http://stackoverflow.com/questions/2487333/fastest-one-liner-way-to-list-attr-accessors-in-ruby) – Oleg Kurbatov Aug 01 '16 at 15:14
  • 1
    I don't think this is a proper duplicate of the nominated examplar: That question asks how to find all accessor method defined with attr_accessor. This question asks how to find all accessor methods for columns which map to a certain type of column. – Wayne Conrad Aug 01 '16 at 15:29
  • I've made an edit that I hope makes the question more clear. If I have erred, please roll back my edit. – Wayne Conrad Aug 01 '16 at 15:33
  • Thanks for edit @WayneConrad as it's more relevant, yes as exactly pointed out, this question is different from finding all accessor methods defined with attr_accessor. – kattybilly Aug 02 '16 at 02:56

1 Answers1

1

For Rails 4 with Postgres you could try this:

ModelName.columns.select {|col| col.sql_type == "timestamp with time zone" }.map(&:name)

For Rails 3 with MySQL you could try this:

ModelName.arel_table.columns.select {|col| col.class == Arel::Attributes::Time }.map(&:name)
user3680688
  • 426
  • 3
  • 12