我对Rails世界非常陌生,我想创建一个包裹跟踪应用程序。我希望能够将包裹的跟踪号传递给我创建的用于刮擦承运人站点的rails方法。
我得到了错误数量的参数错误,并且不明白为什么。 任何输入表示赞赏!
routes.rb
Rails.application.routes.draw do
resources :packages do
match '/scrape', to: 'packages#scrape', via: :post, on: :collection
end
root 'home#index'
get 'dashboard' => 'packages#index'
get '/logout' => 'auth0#logout'
get 'auth/auth0', as: 'authentication'
get 'auth/auth0/callback' => 'auth0#callback'
get 'auth/failure' => 'auth0#failure'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
抓取方法
def scrape(tracking_num)
require 'watir'
url = "https://www.ups.com/track?loc=en_US&tracknum=#{tracking_num}&requester=WT/trackdetails"
b = Watir::Browser.new :chrome, headless: true
b.goto(url)
text = b.p(:class, 'ups-txt_size_double_lg').when_present.text
flash.now[:notice] = text
end
button_to
<%= button_to 'Track', scrape_packages_path(tracking_num: package.tracking), class: "btn btn-sm btn-outline-dark" %>
答案 0 :(得分:0)
POST请求和操作未像您编写的那样使用。
我首先回答您的直接问题:调用控制器中的操作时不带参数。 def scrape(tracking_num)
期望使用一个参数来调用,因此会引发错误。
以下是修改内容:
Rails.application.routes.draw do
resources :packages do
# you can use 'post' directly
post '/scrape', to: 'packages#scrape', on: :collection
end
end
# remove the parameters of method and use params[:tracking_num] to get it
def scrape
require 'watir'
url = "https://www.ups.com/track?loc=en_US&tracknum=#{params[:tracking_num]}&requester=WT/trackdetails"
b = Watir::Browser.new :chrome, headless: true
b.goto(url)
text = b.p(:class, 'ups-txt_size_double_lg').when_present.text
flash.now[:notice] = text
end
# add { remote: true, method: :post } to the link
<%= link_to 'Track', scrape_packages_path(tracking_num: package.tracking), class: "btn btn-sm btn-outline-dark", method: :post, remote: true %>