undefined局部变量或方法`params'for main:Object

时间:2014-03-16 14:43:41

标签: ruby-on-rails scrape rake-task

我有一个rake任务,我试图找到要更新的数据库中的记录。问题是当我使用(params [:name])时,它会抛出消息未定义的局部变量或方法`params' for main:对象。如何让rams任务可以使用params?谢谢。我对此感到陌生,感谢任何帮助。

task scrape_borisAPI: :environment do

@json = HTTParty.get("http://borisapi.heroku.com/stations.json")

@json.each do |station|

@location = Location.find(params[:name])
    @location.nb_bikes = station["nb_bikes"]
    @location.nb_empty_docks = station["nb_empty_docks"]
    @location.update_attributes(:nb_bikes => "@location.nb_bikes", :nb_empty_docks => "@location.nb_empty_docks")
end
end

最初rake任务看起来像这样,我试图修改它来更新记录而不是创建新记录。

task scrape_borisAPI: :environment do

@json = HTTParty.get("http://borisapi.heroku.com/stations.json")

@json.each do |station|
        @location = Location.new
    @location.name = station["name"]
    @location.latitude = station["lat"]
    @location.longitude = station["long"]
    @location.nb_bikes = station["nb_bikes"]
    @location.nb_empty_docks = station["nb_empty_docks"]
    @location.save!
    end
end

2 个答案:

答案 0 :(得分:0)

你不能。 Rake任务不是Web请求,只有Web请求有params。 怎么做?使用ENV

task scrape_borisAPI: :environment do

unless ENV['name']
  puts "You should set ENV 'name' to something to perform this task!"
  next # Use next, see this Stackoverflow question: http://stackoverflow.com/questions/2316475/how-do-i-return-early-from-a-rake-task
end

@json = HTTParty.get("http://borisapi.heroku.com/stations.json")

@json.each do |station|

@location = Location.find(ENV['name'])
    @location.nb_bikes = station["nb_bikes"]
    @location.nb_empty_docks = station["nb_empty_docks"]
    @location.update_attributes(:nb_bikes => "@location.nb_bikes", :nb_empty_docks => "@location.nb_empty_docks")
end
end

然后你可以用这种方式运行你的任务:

bundle exec rake scrape_borisAPI name=Something

答案 1 :(得分:0)

由于你将从代码中调用rake任务,你可以编写一个带参数的rake任务。

namespace :whatever do desc "desc of task" task :task_name, [:arg1] => :environment do |task, args| puts "Your argument is #{arg.arg1}" #Do all that you want. end end

您可以编写rake任务的描述,然后使用您想要的那个参数调用它,您可以进行更新操作。调用任务就像:rake whatever:taskname[argument]