如何将表单的参数提交到控制器中的(API调用)方法?

时间:2016-01-16 20:32:14

标签: ruby-on-rails ruby forms api

我正在进行API调用,但没有将所有数据保存到我的数据库中,因此我假设我不需要为此目的制作模型。但是,我不知道如何为我的控制器中的API调用生成表单。

以下是我认为的表格:

<%= simple_form_for ITHINKINEEDSOMETHINGHERE url: searchApis_path, :method => 'get' do |f| %>
  <%= f.input :keyword, :placeholder => 'keyword', input_html: { name: :keyword } %>
  <%= f.input :city, :placeholder => 'city', input_html: { name: :keyword } %>
  <%= f.input :start_date, :placeholder => 'YYYY-MM-DD', input_html: { name: :start_date } %>
  <%= f.input :end_date, :placeholder => 'YYYY-MM-DD', input_html: { name: :end_date } %>
  <%= f.button :submit, "Submit" %>
<% end %>

我的相应控制器:

class HomeController < ApplicationController
  def index
  end

  def searchApis
    start_date = params[:start_date]
    end_date = params[:start_date]
    keyword = params[:keyword]
    city = params[:city]

    eventbrite_request = Typhoeus::Request.new('https://www.eventbriteapi.com/v3/events/search?q='+keyword+'&sort_by=best&venue.city='+city+'&start_date.range_start='+start_date+'T00:00:00Z&start_date.range_end='+end_date+'T00:00:00Z',
                                  method: :get,
                                  headers: { 'Authorization' => ENV['EVENTBRITE']})
    @response = eventbrite_request.run

    # yelp_request = Typhoeus::Request.new('',
    #                                   )
    # set @result to be the data that I want.
  end


end

我收到“未定义的方法'model_name'”错误。

我发出GET请求的路由是/searchApis,因此我猜测表单中的网址应为searchApis_path

到目前为止,我主要学习了如何创建表单来生成模型的新实例,但在这种情况下,表单实质上是启动API调用,我的响应稍后将显示在我的表单下。为了它的价值,我希望以后能够将响应JSON中的选择数据保存到“书签”模型中。

感谢。

1 个答案:

答案 0 :(得分:0)

你写ITHINKINEEDSOMETHINGHERE的地方通常是记录,通常是ActiveRecord模型。它用于构建各种字段名称。

由于看起来您正在使用搜索控制器,因此可以将:search放在那里,然后将所有表单字段命名为search[keyword]

在你的后端,你只需要访问正确的params对象,该对象通常嵌套在你命名记录的任何内容之下,所以在这种情况下,params[:search][:keyword]

http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for

我知道你正在使用simple_form,但它从form_for继承了很多,所以该页面仍然是一个很好的参考