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!
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.
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? #
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 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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With