Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Rails) Is there a way to check the field's datatype?

How do you check what the datatype is for something that was retrieved from the database?

For example, if I have some instantiation of a model @model with a database field "title", I want to be able to code something like @model.title.type and have it return "String". Does Rails have any built-in functionality for this?

like image 831
Karl Avatar asked Aug 10 '09 22:08

Karl


2 Answers

Try this:

@model.column_for_attribute('title').type

Should return :string, :text, :integer, etc.

The ActiveRecord Column class also includes a number of other attributes: default, limit, name, null, precision, primary, scale, sql_type, type.

like image 61
Dave Ray Avatar answered Nov 11 '22 07:11

Dave Ray


In Rails 3, for my model "Firm", I'd use Firm.columns_hash.

Firm.columns_hash["name"].type  #returns :string

If you want to iterate through them, you'd do something like this:

Firm.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}

which will output the following:

id => integer
name => string
max_trade_qty => integer

and so on.

like image 30
Grant Birchmeier Avatar answered Nov 11 '22 08:11

Grant Birchmeier