【问题标题】:Can't set boolean values when import data from csv to postgresql将数据从 csv 导入 postgresql 时无法设置布尔值
【发布时间】:2012-11-07 09:31:39
【问题描述】:

我已经建立了一个任务来导入这样的数据:

CSV.foreach(file, :headers => true) do |row|  
  question = Question.new ({  
  content:   row[0],
  mark:      row[1],
  topic_id:  row[2],
  question_type_id: row[3],
  answers_attributes: [
    { content: row[5], correct: row[6] },
    { content: row[7], correct: row[8] }
  ]
})
question.user_id = row[4]
question.save!

这是我的 CSV 文件:

content, mark, topic_id, question_type_id, user_id, content, correct, content, correct
_____ are people involved in or affected by project activities, 5, 16, 1, 3, True, 't', False, 'f'

但是当我运行导入任务时,correct attribute 在数据库中总是为 FALSE,我尝试过使用不同的 PostgreSQL 的 Boolean Data Type 但无法正常工作。我怎么了?

【问题讨论】:

  • 请向我们展示(生成的)SQL。我看起来像 't' 和 'f' 字段是多余的/多余的。
  • @DipakPanchal 它有错误:Illegal quoting in line 2.@wildplasser 当我使用rake import 时如何显示 SQL ?
  • 结果没有变化,两个答案行仍有正确列的值为FALSE
  • 还是一样的结果,两个答案都是FALSE(这是我为correct列设置的默认值),我已经尝试了Boolean Data type中的所有值。
  • 如果您不使用 postgres 导入 csv:请删除 postgres 标签。 {content,correct} 字段在我看来仍然是重复的。

标签: ruby-on-rails ruby-on-rails-3 postgresql csv import


【解决方案1】:

我发现了问题。它在 csv 文件中:

content, mark, topic_id, question_type_id, user_id, content, correct, content, correct
_____ are people involved in or affected by project activities, 5, 16, 1, 3, True, 1, False, 0

这里的问题是布尔列值之前的空格。在上面的 csv 文件中,True, 1 之间的空格是个问题。 csv文件导入数据库时​​,包含1前面的空格,所以导入的值是" 1",而不是"1",所以postgresql无法识别带空格的值。我删除了它之前的空格,它现在可以工作了,这是我正确的 csv 文件(我删除了所有空格):

content,mark,topic_id,question_type_id,user_id,content,correct,content,correct
_____ are people involved in or affected by project activities,5,16,1,3,True,1,False,0

如果有人像我一样遇到 CSV 文件中的空格问题,也许这对 SO 有帮助。

【讨论】:

    【解决方案2】:

    尝试用真/假替换真/假

    1.9.3-p194 :006 > True
    NameError: uninitialized constant True
    from (irb):6
    from /Users/SAdvincula/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'
    1.9.3-p194 :007 > true
    => true 
    

    【讨论】:

    • 我试过了,但不起作用:(啊,TrueFalse在我的csv中,这是答案的内容,'t'和'f'是我用来设置的值布尔值
    【解决方案3】:

    更改您的 csv 文件

    content, mark, topic_id, question_type_id, user_id, content, correct, content, correct
    _____ are people involved in or affected by project activities, 5, 16, 1, 3, True, '1', False, '0'
    

    【讨论】:

    • 你的'f'和't'是什么?如果它是布尔值,则使用 1 表示真,使用 0 表示假
    • 可能你误解了,TrueFalsecontent 列的值,改变它只是改变答案的问题内容。 'f' 和 't' 是要设置的值 boolean data type
    • 无论如何,感谢您的帮助,我会在发现问题时发布答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多