从Ruby Model中获取属于某个Class的字段

时间:2016-08-01 14:40:35

标签: ruby-on-rails ruby activerecord rails-activerecord

如何从Ruby模型中获取属于某个类的所有属性或column_names(即,在数据库中具有某种列类型)?

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']

1 个答案:

答案 0 :(得分:0)

对于Postgres的Rails 4,您可以试试这个:

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

对于使用MySQL的Rails 3,你可以试试这个:

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