1

Im trying to standardize data stored in my database. In the sense that I want everything stored as strings. Whats the best way to convert all datatypes into strings in rails?

So if I have something like this in my database:

 t.funny = no #(boolean)

if Im converting hundreds of these to strings in a loop, whats the best way to do this?

Thanks

2
  • What does this have to do with Rails? Are you looking to do this in a migration? Commented Oct 31, 2012 at 0:25
  • #to_s. If you want to convert all columns, I would write a migration and change the column type. change_column :users, :field, :string, limit: 100. Commented Jan 31, 2014 at 5:36

3 Answers 3

3

monkey patches accepted? :)

here is one:

class Object
  def to_sb
    return 'no' if [FalseClass, NilClass].include?(self.class) 
    return 'yes' if self.class == TrueClass
    self
  end  
end  

v = true
v.to_sb
=> "yes"

v = nil
v.to_sb
=> "no"

v = false
v.to_sb
=> "no"

v = 'blah'
v.to_sb
=> "blah"

now in your model you can use t.funny.to_sb

meant to string boolean

please note that non boolean values will be returned as is

See it in action here

Sign up to request clarification or add additional context in comments.

Comments

3

You could monkey-patch ActiveRecord or your database's connection adapter (e.g., pg gem for PostgreSQL) and have it store boolean values as strings (e.g., Y or N).

On the other hand, if you're storing everything as strings that tells me you don't care about having a typed schema. If so, perhaps you might want to take a look at alternatives such as NoSQL (MongoDB and CouchDB in particular have strong Rails integration) where everything is just a 'document' of essentially keys => values.

Comments

0

false and nil are both treated as same so code can be written as

class Object
  def to_bool
    return 'no' unless self
    return 'yes' if self.class == TrueClass
    self
  end
end

Results:

v = true
v.to_sb
=> "yes"

v = nil
v.to_sb
=> "no"

v = false
v.to_sb
=> "no"

v = 'blah'
v.to_sb
=> "blah"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.