Cast a string to the type of an ActiveRecord attribute
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