Allan Perez Gonzalez
Allan Perez Gonzalez

Reputation: 45

Rails Template is missing render json

actually i use rails for my REST API, and i need transform my object to json but when i try i got this error:

            <h1>Template is missing</h1>
        <p>Missing template firms/show, application/show with {:locale=&gt;[:en], :formats=&gt;[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :handlers=&gt;[:erb, :builder, :arb, :jbuilder]}. Searched in:
  * &quot;/Users/allan/Desktop/Work/back/app/views&quot;
  * &quot;/Library/Ruby/Gems/2.0.0/gems/activeadmin-0.6.0/app/views&quot;
  * &quot;/Library/Ruby/Gems/2.0.0/gems/kaminari-0.16.3/app/views&quot;
  * &quot;/Library/Ruby/Gems/2.0.0/gems/devise_invitable-1.5.5/app/views&quot;
  * &quot;/Library/Ruby/Gems/2.0.0/gems/devise-3.5.4/app/views&quot;
</p>

This is my code

 def show
        firm= Firm.find_by_subdomain(params[:subdomain])
        if firm.present?
          respond_to do |format|
            @firm = firm
            format.json { render :json => @firm.to_json }
          end
        end
      end

I hope someone here can help me :)

Solve:

  def show
    render json: Firm.find_by_subdomain(current_subdomain)
  end

thank you

Upvotes: 2

Views: 2000

Answers (3)

Jacquen
Jacquen

Reputation: 1116

If, for whatever reason, you are doing something strange like working within an API-only app but in some controllers using full-stack views and templates by including ActionView::Layouts and then trying to render json in some actions (yes, I am doing this strange thing), the problem lies in your combination of API-only and ActionView::Layouts.

The easy solution is to write your own little method for rendering json within these hybrid controllers (or just directly use the code in this method in your controller action):

def render_json(object)
  response.set_header('Content-Type', 'application/json')
  render(body: object.to_json)
end

Upvotes: 0

Template missing means that you asking for a html view, not doing a json request.

If you want to always return json format regardless of format param, do this:

before_action :set_default_response_format

protected

def set_default_response_format
  request.format = :json
end

@source: Rails 4 - How to render JSON regardless of requested format?

Upvotes: 1

born4new
born4new

Reputation: 1687

Try to add .json at the end of you query when querying your route. Without this, it will try to render html and it will go search for view file that might not be present in your case.

Upvotes: 0

Related Questions