【问题标题】:Trying to import JSON string in to database using Rails尝试使用 Rails 将 JSON 字符串导入数据库
【发布时间】:2014-06-04 16:18:42
【问题描述】:

Exercise.rb - 模型

def self.import!
  @request = Net::HTTP.get(URI.parse('https://example.com/output'))
  @exercises = JSON.parse(@request)

  @exercises.each do |e|
    existing = Exercise.exists?(e)
    unless existing === false
      tmp = existing.first
    end

    e[:sections_attributes] = e.delete("sections")
    e[:questions_attributes] = e.delete("questions")
    e[:answers_attributes] = e.delete("answers")

    record = Exercise.create(e)
    puts "Record #{record["id"]} updated / created"
  end
end

运行导入时出现以下错误:

(0.9ms) COMMIT TypeError: no implicit conversion of String into Integer

我的直觉是因为其中的每个项目都是一个字符串。如何转换项目或让插入忽略列类型?

@request 的摘录

> `[2] pry(Exercise)> e
=> {"publish_date"=>"2013-12-11",
  "grade_id"=>2,
  "exercise_type"=>3,
  "week"=>1,
  "content"=>"<hr />\r\n\r\nQuestions:\r\n\r\n",
  "grammar_list"=>"",
  "title_append"=>nil,
  "sections"=>
   [{"name"=>"Vocab",
     "order"=>0,
     "questions"=>
      [{"question"=>"rgrthth",
        "type"=>3,
        "order"=>0,
        "answers"=>[{"answer"=>"aa", "correct"=>true, "order"=>0}]},
         {"question"=>"uh67jy7k",
          "type"=>3,
          "order"=>0,
          "answers"=>[{"answer"=>"bb", "correct"=>true, "order"=>0}]},
          {"question"=>"rgtdyjuyik",
           "type"=>3,
           "order"=>0,
           "answers"=>[{"answer"=>"cc", "correct"=>true, "order"=>0}]}]}]}`

更新代码的输出

2.1.0 :040 > Exercise.import!
   (0.2ms)  SELECT COUNT(*) FROM `exercises` WHERE `exercises`.`week` = 1 AND `exercises`.`exercise_type` = 3 AND `exercises`.`grade_id` = 2

From: /Users/pc-a/Sites/mailbox/app/models/exercise.rb @ line 99 Exercise.import!:

     92: def self.import!
     93:   @request = Net::HTTP.get(URI.parse('example.com/output'))
     94:   @exercises = JSON.parse(@request)
     95:
     96:   @exercises.map(&:with_indifferent_access).each do |e|
     97:     next if Exercise.exists?(e[:week], e[:exercise_type], e[:grade_id])
     98:
 =>  99:     binding.pry
    100:
    101:
    102:     e[:sections_attributes] = e.delete(:sections)
    103:     e[:sections_attributes].map! do |section_attributes|
    104:       section_attributes[:questions_attributes] = section_attributes.delete(:questions)
    105:       section_attributes[:questions_attributes].map! do |question_attributes|
    106:         question_attributes[:answers_attributes] = question_attributes.delete(:answers)
    107:       end
    108:     end
    109:
    110:     binding.pry
    111:
    112:     exercise = Exercise.new(e)
    113:     if exercise.save
    114:       puts "Exercise #{exercise.id} created!"
    115:     else
    116:       puts "Could not create Exercise: #{exercise.errors.full_messages.join('; ')}"
    117:     end
    118:   end
    119: end

[1] pry(Exercise)> e
=> {"publish_date"=>"2013-12-11",
 "grade_id"=>2,
 "exercise_type"=>3,
 "week"=>1,
 "content"=>"<hr />\r\n\r\nQuestions:\r\n\r\n",
 "grammar_list"=>"",
 "title_append"=>nil,
 "sections"=>
  [{"name"=>"Vocab",
    "order"=>0,
    "questions"=>
     [{"question"=>"rgrthth",
       "type"=>3,
       "order"=>0,
       "answers"=>[{"answer"=>"aa", "correct"=>true, "order"=>0}]},
      {"question"=>"uh67jy7k",
       "type"=>3,
       "order"=>0,
       "answers"=>[{"answer"=>"bb", "correct"=>true, "order"=>0}]},
      {"question"=>"rgtdyjuyik",
       "type"=>3,
       "order"=>0,
       "answers"=>[{"answer"=>"cc", "correct"=>true, "order"=>0}]}]}]}
[2] pry(Exercise)> exit

From: /Users/pc-a/Sites/mailbox/app/models/exercise.rb @ line 110 Exercise.import!:

     92: def self.import!
     93:   @request = Net::HTTP.get(URI.parse('example.com/output'))
     94:   @exercises = JSON.parse(@request)
     95:
     96:   @exercises.map(&:with_indifferent_access).each do |e|
     97:     next if Exercise.exists?(e[:week], e[:exercise_type], e[:grade_id])
     98:
     99:     binding.pry
    100:
    101:
    102:     e[:sections_attributes] = e.delete(:sections)
    103:     e[:sections_attributes].map! do |section_attributes|
    104:       section_attributes[:questions_attributes] = section_attributes.delete(:questions)
    105:       section_attributes[:questions_attributes].map! do |question_attributes|
    106:         question_attributes[:answers_attributes] = question_attributes.delete(:answers)
    107:       end
    108:     end
    109:
 => 110:     binding.pry
    111:
    112:     exercise = Exercise.new(e)
    113:     if exercise.save
    114:       puts "Exercise #{exercise.id} created!"
    115:     else
    116:       puts "Could not create Exercise: #{exercise.errors.full_messages.join('; ')}"
    117:     end
    118:   end
    119: end

[1] pry(Exercise)> e
=> {"publish_date"=>"2013-12-11",
 "grade_id"=>2,
 "exercise_type"=>3,
 "week"=>1,
 "content"=>"<hr />\r\n\r\nQuestions:\r\n\r\n",
 "grammar_list"=>"",
 "title_append"=>nil,
 "sections_attributes"=>
  [[[{"answer"=>"aa", "correct"=>true, "order"=>0}],
    [{"answer"=>"bb", "correct"=>true, "order"=>0}],
    [{"answer"=>"cc", "correct"=>true, "order"=>0}]]]}

【问题讨论】:

  • 可以发@request的具体内容吗? (您可以通过在发生错误的行之前执行raiser @request 来查看
  • 您的e 存在于块中,但不在它们之后。或者这是一些全球性的事情?。
  • 添加了@request 的第一次迭代,因为它很大
  • 是的,当我粘贴时,格式似乎被弄乱了。我现在看看能不能排序
  • 知道了,被格式弄糊涂了。

标签: mysql ruby-on-rails ruby-on-rails-4


【解决方案1】:

尝试以下方法:

def self.import!
    @request = Net::HTTP.get(URI.parse('https://example.com/output'))
    @exercises = JSON.parse(@request)

    @exercises.map(&:with_indifferent_access).each do |e|
      next if Exercise.exists?(name: e[:name]) # or whatever the attribute(s) you use to determine the uniqueness of an Exercise

      e[:sections_attributes] = e.delete(:sections)
      e[:sections_attributes].map! do |section_attributes|
        section_attributes[:questions_attributes] = section_attributes.delete(:questions)
        section_attributes[:questions_attributes].map! do |question_attributes|
          question_attributes[:answers_attributes] = question_attributes.delete(:answers)
        end
      end

      exercise = Exercise.new(e)
      if exercise.save
        puts "Exercise #{exercise.id} created!"
      else
        puts "Could not create Exercise: #{exercise.errors.full_messages.join('; ')}"
      end
    end
  end
end

【讨论】:

  • 得到 ActiveRecord::AssociationTypeMismatch: Question(#2297301000) 预期,得到 ActiveSupport::HashWithIndifferentAccess(#2162666120)
  • 您必须设置 accepts_nested_attributes_for :questions(和 :sections:answers)或者您可以“独立”创建练习、问题、部分和答案(如果您需要示例最后一个,虽然很简单)@Xopa
  • 是的,当我通过表单创建练习时,我已经完成了连接设置和工作。只是这个导入函数不想工作
  • 您的请求回复显示 Answer 嵌套在 Question 嵌套在 Section 中。它也是您的数据库配置吗? (即Excercise has_many :sections && Section has_many :questions && Question has_many :answers?@Xopa
  • 我更新了我的答案以嵌套属性,遵循嵌套关系@Xopa
猜你喜欢
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多