Cast a string to the type of an ActiveRecord attribute

Updated . Posted . Visible to the public.

ActiveRecord models know how to cast a given string to the type of a given attribute (or column).

The following model will serve as our example:

create_table :notes do |t|
  t.string :title
  t.integer :user_id
  t.boolean :deleted
end

You can make the Note class cast strings into their respective types like this:

Note.columns_hash['user_id'].type_cast('123') # => 123
Note.columns_hash['deleted'].type_cast('1') # => true
Note.columns_hash['deleted'].type_cast('0') # => false
Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-04-08 10:18)