Read more

Howto respond html or json in the same controller action with Rails 2

Martin Straub
July 14, 2014Software engineer at makandra GmbH

Code snippet tested with Rails 2.3

  def index
    # ...
    if request.xhr?
      html = render_to_string(:partial => "list", :layout => false)
      respond_to do |format|
        format.html { render :text => html }
        format.json { render :json => {:html => html, ... } }
      end
    end
  end
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Note: Perhaps you ran into ActionView::MissingTemplate error and this card might help. If you call render_to_string within the format.json block, Rails will only look for an index.json template, but not for an index.erb template.

Posted by Martin Straub to makandra dev (2014-07-14 12:50)