spike
spike

Reputation: 10004

Get database type of ActiveRecord object attribute

Let's say I have this in schema.rb:

create_table "products" do |t|
 t.string   "name",                                           
 t.text     "description"
end

I want a way to find out what the database type of a product attribute is.

Something like: Product.column_type(:name) => "string"

Is this possible?

Upvotes: 1

Views: 1385

Answers (1)

jdoe
jdoe

Reputation: 15771

Product.columns_hash['name'].type # => :string

Note the using of strings instead of symbols.

About an alternative: sql_type

It maps logical Rails types to DB-specific data types. For general purpose things I wouldn't recommend using it: your production DB-engine will return the value which won't be the same as the sql_type for the very same column in your development DB (although they both were created with the same migration file). Example for boolean field:

# SQLite mapping:
:boolean => { :name => "boolean" }
# MySQL mapping:
:boolean => { :name => "tinyint", :limit => 1 }

Using type in both cases give you :boolean, as you specify in migrations.

Upvotes: 6

Related Questions