【发布时间】: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