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

Posted Almost 10 years ago. Visible to the public.

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

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.

Last edit
7 months ago
Michael Leimstädtner
Keywords
missing, template
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2014-07-14 10:50)