stevec
stevec

Reputation: 52238

How to seed boolean values into rails app

How can I seed a rails app boolean column given data of the form "t", "f", "f", "t" etc etc

I suspect if I seed these strings to a boolean column I will receive an error

For context, the "t", "f", "f", "t" format is how boolean data appears when extracted as a CSV from the postgresql database

For further context, the current seed file looks as such

csv_text = File.read(Rails.root.join('lib', 'seeds', 'bands.csv'))
csv = CSV.parse(csv_text.scrub, headers: true)
csv.each do |row|
  t = Band.new
  t.band_name = row['band_name']
  t.category_1 = row['category_1']
  t.category_2 = row['category_2']
  t.category_3 = row['category_3']
  t.category_4 = row['category_4']
  t.link = row['link']
  t.time = Time.zone.parse(row['time'])
  t.image = row['image']
  t.available = row['available'] # This is the boolean column
  t.save
  puts "#{t.band} saved"
end

Upvotes: 0

Views: 451

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

You can check for the string received something like this

t.available = row['available'] == 't'

This will assign t.available with boolean true else false

If you want to check for both values and keep it nil in case the value is not provided you can use

t.available = if row['available'] == 't' 
                true
              elsif row['available'] == 'f'
                false
              end 

Upvotes: 3

Related Questions