gpt4 book ai didi

ruby-on-rails - Rails 不知道如何构建任务

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:18 25 4
gpt4 key购买 nike

我正在尝试从网站上抓取数据。我正在从 index.html.erb 运行 rake

 <% Article.run_rake("fetch_games") %>

我在 .rb 文件中定义了它。这是文章.rb

require 'rake'
require 'rubygems'
#load './lib/tasks/article_task.rake'

class Article < ActiveRecord::Base

def self.run_rake(fetch_games)
Rails.root + "lib/tasks/article_task.rake"
Rake::Task["fetch_games"].invoke
end
end

这里是 rakefile 本身:article_task.rake

desc "Fetch Games"
task :fetch_games => :environment do

require 'nokogiri'
require 'open-uri'

url = "http://espn.go.com/nba/schedule"
data = Nokogiri::HTML(open(url))
games = data.css('.responsive-table-wrap')

games.each do |game|

#check for a listing
if !game.at_css("caption").nil?
#Date
puts game.at_css("caption").text
else
puts "No Listing"
end

#check for the team name
if !game.at_css(".team-name").nil?
#Team name
puts game.at_css(".team-name").text
else
puts "No Games Scheduled"
end
#empty
puts ""
end
end

当我从终端运行它时,它会提取我需要的东西。但是当我尝试通过 rails server 运行它时,它给了我这个错误:

Runtime Error

我做错了什么?顺便说一句,ruby/rails 的新手

最佳答案

我们需要在你运行它之前加载任务。你注释掉那一行 -

 load './lib/tasks/article_task.rake'

这样做-

  require 'rake'
require 'rubygems'
load './lib/tasks/article_task.rake'

class Article < ActiveRecord::Base

def self.run_rake(fetch_games)
Rake::Task["fetch_games"].invoke
end
end

关于ruby-on-rails - Rails 不知道如何构建任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30222466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com