Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)   # :string
User.inspect(:updated_at) # :datetime
User.inspect(:created_at) # :datetime

Thanks!

like image 336
Kevin Sylvestre Avatar asked Nov 10 '10 08:11

Kevin Sylvestre


People also ask

What is ActiveRecord in Ruby on Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is ActiveModel :: model?

ActiveModel::Model allows implementing models similar to ActiveRecord::Base . class EmailContact include ActiveModel::Model attr_accessor :name, :email, :message validates :name, :email, :message, presence: true def deliver if valid? #

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

What are virtual attributes rails?

What is 'Virtual Attribute'? The Virtual Attribute is a class attribute, which has no representation in the database. It becomes available after object initialization and remains alive while the object itself is available (like the instance methods).


1 Answers

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
like image 158
mikej Avatar answered Nov 07 '22 02:11

mikej