我需要从外部API搜索数据(教程),由我的rails应用程序中的一个表单提供2个参数(标签和设备)。
在我的路线中,我有:
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>
有人能帮帮我吗?:)
发布于 2016-09-15 15:44:38
如果它是外部API,则您的API使用者无法识别API应用程序的路由助手。更好的方法是让表单操作调用消费者应用程序中的控制器操作的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数组,并在视图中显示它。在我使用HTTP发出HTTParty请求的例子中,您可以使用其他可用的Ruby库来完成同样的任务。
您的表单现在可以如下所示:
<%= form_tag search_path, method: :post do %>
<%#= Your input tags %>
<% end %>
https://stackoverflow.com/questions/39513363
复制相似问题