【问题标题】:Iterate through an array of hashes and save each hash as a record in a ruby on rails (postgresql) table遍历散列数组并将每个散列保存为 ruby​​ on rails (postgresql) 表中的记录
【发布时间】:2018-09-26 07:24:24
【问题描述】:

我已成功提取了 90 篇文章(标题、链接和文本),现在想将这些数据放入表格中

我创建了表格:

rails g model Article title:string link:string paragraphs:text

在 irb 中,我可以运行我的提取(使用 Nokogiri)来获取数据并将其设置为等于articlesArray

但我不知道下一步该做什么。我无法找出正确的语法来成功地将数据放入表中

我仍在 irb 中(不在 rails c 中)——如果这有什么不同的话

我真的很辛苦

这是我目前尝试过的几件事

for i in 0...articlesArray.length
    Article.create(
        title: articlesArray[i].title,
        link: articlesArray[i].link,
        paragraphs: articlesArray[i].paragraphs.text[176...articlesArray[i].paragraphs.text.length-283]      
        )
end

尝试另一种方法

for i in 0...articlesArray.length-1

@article = Article.new

@article.title = articlesArray[i].title
@article.link = articlesArray[i].link
@article.paragraphs = articlesArray[i].paragraphs.text[176...articlesArray[i].paragraphs.text.length-283] 

@article.save
end

再来一次

articlesArray.each do |article|

    @article = Article.new

    @article.title = article.title
    @article.link = article.link
    @article.paragraphs = article.paragraphs.text[176...article.paragraphs.text.length-283] 

    @article.save
end

这些似乎都不起作用

【问题讨论】:

  • 为什么你认为它不起作用?有什么错误吗?
  • 尝试先调试一下,例如:1: article_data = articlesArray.first 2: article = Article.new(title: article_data.title, link: article_data.link, paragraphs: article_data.paragraphs.text[176...article.paragraphs.text.length-283]) 3: article.save 4: puts article.errors
  • @AlexGolubenko 运行您的建议给出:SyntaxError ((irb):142: syntax error, unexpected tIDENTIFIER, expecting end-of-input ...raphs.text.length-283]) 文章。保存 puts article.errors
  • 我更新了我的评论,一步一步来。
  • 第一步有效。第二步说:NoMethodError (undefined method `paragraphs' for nil:NilClass)

标签: ruby-on-rails ruby postgresql ruby-on-rails-5


【解决方案1】:

这行得通:

articlesArray.each do |article|
    Article.create(
        title: article.title,
        link: article.link,
        paragraphs: article.paragraphs
        )
end

【讨论】:

    猜你喜欢
    • 2012-08-03
    • 2018-06-29
    • 1970-01-01
    • 2019-01-31
    • 2023-04-10
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    相关资源
    最近更新 更多