通过rails表单搜索外部API,并在视图中显示结果



我需要搜索数据(教程)从一个外部API与2个参数(标签和设备)在我的rails应用程序的表单提供。

在我的路由中有:

resources :search_lists, only: [:index] do
  collection do
    post :search
  end
end

这是我认为我应该在我的SearchListsController:

def index
  @search_parameter = params[:tags]
end
def search
end

我不确定我将如何组织我的代码,以及我应该在哪里传递API调用。

这是我的观点,rails不识别search_lists_url:

<form action="<%= search_lists_url %>">
  <input type="text" name="" value="" placeholder="Search by tag">
  <label >Filters:</label>
  <input type="checkbox" value="first_checkbox">Smarthpone
  <input type="checkbox" value="second_checkbox">Tablet
  <input type="checkbox" value="third_checkbox">Mac
  <br>
  <input type="submit" value="Search">
</form>
有谁能帮帮我吗?:)

如果它是一个外部API,那么你的API消费者无法识别该API应用程序的路由helper。更好的方法是让表单操作调用消费者应用程序中控制器操作的url,然后处理该控制器操作的API调用。

例如,在你的API消费者应用中,你可以在你的路由中这样写:

post "search_lists" => "lists#search", as: :search

然后在您的controllers目录中有一个lists_controller.rb文件,搜索操作如下:

 class ListsController < ApplicationController
     include HTTParty
     def search
     ## make your API Call on this action
      response = HTTParty.post(your_api_host_url/search_lists/search, {body: [#your form input data##]})
     end
 end 

您可以将返回的JSON解析为ruby数组并在视图中显示它。在这个例子中,我使用了HTTParty gem来发出HTTP请求,你可以使用其他可用的ruby库来完成同样的任务。

你的表单现在看起来像这样:

<%= form_tag search_path, method: :post do %>
  <%#= Your input tags %>
<% end %>

最新更新