All threads / How to render partial as a json response for json format?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Srinivasa Varma asked in Rails

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

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

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,629+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.