我必須顯示來自該網站的資料:https://baconipsum.com/json-api/,但我不知道在我的應用程式中在哪里撰寫它的代碼。我必須為控制器和視圖撰寫什么代碼?
uj5u.com熱心網友回復:
設定法拉第:
bacon = Faraday.new("https://baconipsum.com/") do |f|
f.response :json # automatically parse responses as json
end
在控制器中發送請求:
@bacon = bacon.get("api/", type: 'all-meat', sentences: 1).body # => ["Leberkas frankfurter chicken tongue."]
在視圖中使用它:
<% @bacon.each do |meat| %>
<p>
<%= meat %>
</p>
<% end %>
https://lostisland.github.io/faraday/usage/
更新
有很多方法可以設定它。非常簡單的設定可能如下所示:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
private
# NOTE: this method will be accessible in any controller
# that inherits from ApplicationController
def baconipsum
# NOTE: memoize for a bit of performance, in case you're
# making multiple calls to this method.
@baconipsum ||= Faraday.new("https://baconipsum.com/") do |f|
f.response :json
end
end
end
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
# I'm not quite sure what you're trying to do with it;
# change this to fit your use case.
@bacon = baconipsum.get("api/", type: 'all-meat').body
end
end
# app/views/articles/show.html.erb
<% @bacon.each do |meat| %>
<p> <%= meat %> </p>
<% end %>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475642.html
標籤:轨道上的红宝石
