我想在我的一個視圖中包含某種'小部件',允許用戶使用外部「搜索」API。外部API返回一組JSON結果。我想用這個JSON向用戶顯示結果列表。從視圖調用外部API的Rails方式?
什麼是「軌道方式」,使這種情況發生?
例如,我想在主頁上放一個搜索輸入,用一個按鈕來搜索外部API。我創建了一個調用API的PORO,這個PORO將返回結果,但是如何將用戶搜索字符串發送到此PORO?
我想在我的一個視圖中包含某種'小部件',允許用戶使用外部「搜索」API。外部API返回一組JSON結果。我想用這個JSON向用戶顯示結果列表。從視圖調用外部API的Rails方式?
什麼是「軌道方式」,使這種情況發生?
例如,我想在主頁上放一個搜索輸入,用一個按鈕來搜索外部API。我創建了一個調用API的PORO,這個PORO將返回結果,但是如何將用戶搜索字符串發送到此PORO?
只是總結了我們在評論中討論的內容。實現你想要的最簡單的方法將需要一個視圖來呈現小部件和一個路由+控制器來處理搜索請求。
這是所有未經測試的代碼,但你可以得到它的要點。
# routes.rb
# this can be named and pointed to anywhere you want.
# It's using get just so you can see the search params in the url, which is preety common for the search feature.
get '/search', to: 'searches#show', as: 'search'
# models/search.rb
# Your PORO
class Search
attr_reader :results
def initialize(query)
# perform request and assign results
@results = HTTParty.get(url, query: { keyword: query })
end
end
# controllers/searches_controller.rb
def show
if params[:query]
@search = Search.new(params[:query])
end
end
# views/searches/show.html.erb
<%= form_tag search_path, method: :get do %>
<%= text_field_tag :query, params[:query] %>
<%= submit_tag %>
<% end %>
# .... renders contents if they're present.
<%= @search.results if @search %>
你可以另外做的是把什麼搜索到模型中,因此它會繼承命名,你可以處理它作爲一個經常性的資源。
# routes.rb
# A singular resource will do.
resource :search, only: [:show]
# models/search.rb
include ActiveModel::Model
attr_reader :results
attr_accessor :query
validates :query, presence: true
def perform
@results = HTTParty.....
end
# controllers/searches_controller.rb
def show
if search_params = params[:search] && params[:search][:query]
@search = Search.new(query: search_params)
@search.perform if @search.valid?
else
@search = Search.new
end
end
# views/searches/show.html.erb
<%= form_for @search, method: :get do |f| %>
<%= f.text_field :query %>
<%= f.submit %>
<% end %>
<%= @search.results %>
現在...你可能想只/搜索無處不在,不使你的widget,讓你可以提取的形式進入的部分,呈現在application.html.erb。
如果您使用ActiveModel方法,請不要忘記在呈現表單的每個請求中初始化@search。你可以使用before_action
。
一切似乎都工作,除了挖。 未定義的方法'dig'爲{「controller」=>「last_fms」,「action」=>「show」}:ActionController :: Parameters – stoerebink
嘗試'params [:search] && params [:search] [:query] 。 –
工程就像一個魅力。謝謝你,先生! – stoerebink
您希望用戶如何與小部件進行交互?用戶提交搜索參數後,是否願意重新加載整個頁面?在我看來,一個小部件就是你只用JS完成的事情,直接查詢api並在不經過ruby的情況下渲染結果。但是,如果您必須在將視圖呈現給視圖之前解析ruby中的響應,則必須使用常規請求或ajax將搜索參數提交給控制器。 –
也許小部件是錯誤的術語。我想在提交搜索參數後重新加載頁面。我只是不確定最好的做法是做什麼。使用form_for爲在這種情況下不起作用的特定模型提供了一種形式。 – stoerebink
你可以嘗試'form_tag',它不綁定到模型。 http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html –