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 D 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

Reply

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

Reply
Join the discussion

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.