Search code examples
ruby-on-railsjsonactiverecordcontrollerrespond-with

Stop Rails from trying to provide a template / ActionView::MissingTemplate


I have a simple angular rails app that I am trying to get wired up.

Here is my rails controller:

class ItemsController < ApplicationController
  respond_to :json, :html

  def index
    @items = Item.order(params[:sort]).page(params[:page]).per(15)
  end

  def show
    @item = Item.where(params[:id])

    if @item.empty?
      flash[:alert] = "Item number #{params[:id]} does not exist"
    else
      respond_with @item do |format|
        format.json { render :layout => false }
      end
    end
  end
end

I keep getting the ActionView::MissingTemplate error because rails keeps trying to serve up an erb template. I don't want a template!! I just want json. Can some one please give the definitive respond_to/respond_with syntax that will rid me of templates forever?


Solution

  • there are two ways in rails for rendering, CMIIW

    first, as default, it will render a view template, example

      def show
      end
    
    

    then it will render default show view template, example: app/views/controller_name/show.html.erb

    second is by manual render, use render method

    if you want to respond to json only, then:

    class ItemsController < ApplicationController
      def show
        id = params.require(:id)
        @item = Item.find_by(id: id)
    
        if @item.nil?
          render json: { message: "Item number #{id} does not exist", status: :not_found }
        else
          render json: @item
        end
      end
    end
    

    no need to use respond_to, and it's been removed from newest rails too

    rails guide about render is really useful, you can read it here