0

I have a csv that I am trying to upload into the database. I am able to read the csv and get the hash values and insert the values into the database. The issue that I have is one of the hash values has the active field set to "false" but when it is inserting into the database it is inserting as 'true'. Below is the code for that.

model code :

 def self.import(csv_file)
  CSV.foreach(csv_file, headers: true) do |row|
   project_hash = row.to_hash
   Project.create! row.to_hash
  end
end

controller code:

  def import_projects
   projects = Project.import(params[:file].path)
   flash[:notice] = "Projects successfully imported"
   redirect_to :action => :index   
 end

project_hash = {"name"=>"Dog", "project_id"=>nil, "active"=>"false"}

so when the hash is saved in to the database the entry looks likes this.

name => 'Dog', project_id ='', active = 'true'

Please can someone let me know why is the false value for active column being inserted as true.

Archie123
  • 105
  • 2
  • 13

1 Answers1

1

my understanding, ruby consider if there is value inside variable it's true, there are some article in SO discussing about true / false, here is the one for your understanding.

as for your problem above, I would suggest using callback to solve your problem, as sample below

your_model.rb

before_validation :convert_boolean
...

def convert_boolean
  self.active = false if self.active == "false"
end
widjajayd
  • 6,090
  • 4
  • 30
  • 41