Ruby on Rails Active Record Attribute Introspection
What is the best way to get the type of an attribute in Active Record (even before the attribute has been assigned)? For example (this doesn't work, just the goal):
User.new
User.inspect(:id) # :integer
User.inspect(:name) # :string
User.inspect(:password) # :str开发者_如何学运维ing
User.inspect(:updated_at) # :datetime
User.inspect(:created_at) # :datetime
Thanks!
Even without having an instance of the model you can use Model.columns_hash
which is a hash of the columns on the model keyed on the attribute name e.g.
User.columns_hash['name'].type # => :string
User.columns_hash['id'].type # => :integer
User.columns_hash['created_at'].type # => :datetime
Update
As Kevin has commented himself, if you have a model instance (e.g. @user
) then the column_for_attribute
method can be used e.g.
@user.column_for_attribute(:name) # => :string
From the Rails API docs you can see this is just a wrapper that calls columns_hash
on the instance's class:
def column_for_attribute(name)
self.class.columns_hash[name.to_s]
end
Model.type_for_attribute('attr_name') # ActiveModel::Type::Value
Model.attribute_types
精彩评论