ruby-on-railsrubyapimodel-view-controllerjsonplaceholder

ruby on rails call external api and show results


I'm trying to call API (to like https://jsonplaceholder.typicode.com/). the idea is simple click the button to show the res but I'm having trouble implementing it. What I have below is just the button calling the function and want to print it in the console.

error:

enter code here No route matches [POST] "/dashboard/fetch_action"

routes

resources :dashboard do
 collection do
   get :fetch_action
 end
end

dashboard_controller.er

require 'faraday'

def index
end

def fetch_action
    response = Faraday.get 'https://jsonplaceholder.typicode.com/posts/1'
    puts response
    # return response 
end

index.html.erb

    <%= button_to "fetch action", fetch_action_dashboard_index_path, class: "btn btn-warning" %>

Thank you

EDIT:

routes:

Rails.application.routes.draw do

  devise_for :users
  
  devise_scope :user do
    root to: 'devise/sessions#new'
  end

  get 'dashboard' => 'dashboard#index'
  get '/dashboard/fetch-action', to: 'dashboard#fetch_action', as: 'dashboard_fetch_action'
  get '/user' => 'dashboard#index', :as => :user_root

end

rake routes

    new_user_session GET    /users/sign_in(.:format)                                                                 devise/sessions#new
             user_session POST   /users/sign_in(.:format)                                                                 devise/sessions#create
     destroy_user_session DELETE /users/sign_out(.:format)                                                                devise/sessions#destroy
        new_user_password GET    /users/password/new(.:format)                                                            devise/passwords#new
       edit_user_password GET    /users/password/edit(.:format)                                                           devise/passwords#edit
            user_password PATCH  /users/password(.:format)                                                                devise/passwords#update
                          PUT    /users/password(.:format)                                                                devise/passwords#update
                          POST   /users/password(.:format)                                                                devise/passwords#create
 cancel_user_registration GET    /users/cancel(.:format)                                                                  devise/registrations#cancel
    new_user_registration GET    /users/sign_up(.:format)                                                                 devise/registrations#new
   edit_user_registration GET    /users/edit(.:format)                                                                    devise/registrations#edit
        user_registration PATCH  /users(.:format)                                                                         devise/registrations#update
                          PUT    /users(.:format)                                                                         devise/registrations#update
                          DELETE /users(.:format)                                                                         devise/registrations#destroy
                          POST   /users(.:format)                                                                         devise/registrations#create
                     root GET    /                                                                                        devise/sessions#new
                dashboard GET    /dashboard(.:format)                                                                     dashboard#index
   dashboard_fetch_action GET    /dashboard/fetch-action(.:format)                                                        dashboard#fetch_action
                user_root GET    /user(.:format)                                                                          dashboard#index
       rails_service_blob GET    /rails/active_storage/blobs/:signed_id/*filename(.:format)                               active_storage/blobs#show
rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
       rails_disk_service GET    /rails/active_storage/disk/:encoded_key/*filename(.:format)                              active_storage/disk#show
update_rails_disk_service PUT    /rails/active_storage/disk/:encoded_token(.:format)                                      active_storage/disk#update
     rails_direct_uploads POST   /rails/active_storage/direct_uploads(.:format)                                           active_storage/direct_uploads#create
           
                                                                                     

index.html.eb

<%= link_to "fetch action", dashboard_fetch_action_path, class: "btn btn-info" %>

<%= @response %>

fetch-action.html.erb

<%= @response %>

dashboard_controller

def index
end

def show
end

def fetch_action
    uri = URI('https://jsonplaceholder.typicode.com/posts/1')
    req = Net::HTTP.get(uri)
    @response = JSON.parse(req)
end

Error (when clicking the link_to redirects to dashboard/fetch-action with the following error):

DashboardController#show is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: [] NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot.


Solution

  • troubleshooting and setting routes

    First, in your terminal, run rake routes to print out the routes in your app. Post that output here. But you’ll want to check the output of that command for the fetch_action_dashboard_index_path you’re using in the button - is that the correct path?

    I assume it’s not. And there is a simpler way to declare one route. What you’re doing with the resources declaration in your route is configuring routes for the index, show, create, update and delete actions for The dashboard controller. The below line in your routes.rb file will setup just the fetch_action route and name it “dashboard_fetch_action”

    get '/dashboard/fetch-action', to: 'dashboard#fetch_action', as: 'dashboard_fetch_action'

    creating a link to that route

    Second; use link_to instead of button_to to ensure you make a GET request. The btn classes you’re applying will style that link to look like a button anyway and an a tag is more semantically correct than button (because you want to GET) so use:

    <%= link_to "fetch action", dashboard_fetch_action_path, class: "btn btn-warning" %>

    rendering the results of the action

    Finally make sure you have a file in app/views/dashboard/fetch_action.html.erb which will render the API response as HTML. This content (or similar) will achieve that.

    <%= @response =>

    And, in your fetch_action action in the dashboard controller. Instead of response = Faraday..., use @response = Faraday.... That way the response object can be accessed in the view HTML (that’s what the @ signifies)

    def fetch_action
        @response = Faraday.get 'https://jsonplaceholder.typicode.com/posts/1'
    end