Skip to main content

How to render partial as a json response for json format?

Rails • Asked by Srinivasa Varma

Fallback

Hi Guys.

Recently i ran into a problem which does not allowing me to render a partial as a JSON response for .json requests. Below you can get in more detail.

I have a partial resides in below path:
views/sales/manage_data/_spoc_li.html.erb

I have tried two approaches to render that partial as a response.

  1. Using normal controller action as html response ( i have accessed localhost:3000/sales/spocs)
    Following is my controller action code:

    def index
    @products = Product.all
    @spocs = Spoc.all
    render json: {
      html_data: render_to_string(partial: 'sales/manage_data/spoc_li', locals: {spoc: @spocs[0]})
    }
    end
    

    It did not raised any error and i can see json response in browser.

  2. Using .json request ( i have accessed localhost:3000/sales/spocs.json)

def index
    @products = Product.all
    @spocs = Spoc.all
    respond_to do |format|
      format.html
      format.json { render json:{
          html_data: render_to_string(partial: 'sales/manage_data/spoc_li', locals: {spoc: @spocs[0]})
        }
      }
    end
  end

This time it raised an error saying that

Missing partial sales/manage_data/_spoc_li with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/enigma/workspace/collections/app/views" * "/home/enigma/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/ckeditor-4.2.2/app/views" * "/home/enigma/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/devise-4.2.0/app/views"

Some please tell how formats are working and how can i get rid of this?

Thanks


Fallback

The default/convention here would be an url like: localhost:3000/sales.json
Any show action would, as a default, be like: localhost:3000/sales/1.json


Login or create an account to join the conversation.