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

I have a simple angular rails application that I am trying to connect.

Here is my rail 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 the erb pattern. I do not want a template! I just want Johnson. Can someone give the final syntax response_to / reply_with that will permanently save me from templates?

+5
source share
1 answer

there are two ways in the rails for rendering: CMIIW

first, by default, it will display a view template, example

def show end then it will display the view as usual, even you declared response_to: json, it will display the json representation, so this is why you got the MissingTemplate exception

then the following method uses render json: ... , example

 class ItemsController < ApplicationController respond_to :json, :html def show @item = Item.where(params[:id]) if @item.empty? render json: { message: "Item number #{params[:id]} does not exist", status: :not_found } else render json: @item.to_json end end end 

the rail guide on render really useful, you can read it here

+6
source

Source: https://habr.com/ru/post/1209976/


All Articles