Rails Rendering a partial within JSON

前端 未结 3 499
挽巷
挽巷 2021-01-26 12:37

I am trying to render a partial inside a JSON file so that I can use it via AJAX. Currently in my JSON file I have:

<% self.formats = [\"html\"]%>
{
   \"h         


        
相关标签:
3条回答
  • 2021-01-26 13:18

    You can't call to_json on a partial... it's a method of ActiveRecord. If you want json there, then it should be inside the partial.

    0 讨论(0)
  • 2021-01-26 13:21

    In my case, I had the same problem for about a day and a half and after trying lots of combinations of escape_javascript, to_json, render ... content_type, etc I finally achieved what I was looking for, that is rendering a HTML partial in a json response.

    So in your controller you have an action like

    def index
        @candidatos = Candidatos::Base.paginate(page: params[:page], per_page: 3).to_a
        respond_to do |format|
          format.html # index.html.erb
          format.json # index.json.erb
        end
    end
    

    and if the request had a .json it will use the index.json.erb template, and in my case that template is something like

    <% self.formats = ["html"] %>
    {
        "html":<%= thumbnails_tag(@candidatos).to_json.html_safe %>
    }
    

    Note the self.formats = ["html"] is necessary because otherwise the "view" won't find the partial because it will look for a .json partial. and more important, don't use escape_javascript because it will fill the html with \t and \n. In other words, the idea is to pass the output of your partial to .to_json and then to .html_safe.

    thumbnails_tag is just a helper I created because I'm using the partial in lots of parts of the app, but basically it has something like

    def thumbnails_tag objs
      #Uncomment the line below to test when no much data available
      # @listas.fill(@listas.first, 0..6)
      thumb_span = 4
      case @candidatos.length
      when 1..3
        thumb_span = 12 / @candidatos.length
      else 
        thumb_span = 4
      end 
      thumbs = {span: thumb_span}
      render partial: 'candidatos/thumbnails', locals: {candidatos: @candidatos, thumbnail_options: thumbs }
    end
    

    Finally, and just as an example, with this approach, in your .js assets you can do something like:

    $.get('http://localhost:3000/candidatos.json?page=2', function(d){}, 'json')
      .success(function(d){
          $('#presidentes div.row-fluid .thumbnails').parent().append(d.html);
      })
      .error(function(event,error){
      console.log(error);
    })
    

    No need to gsub for \t and \n in your rails view or JSON.parse string in your Javascript.

    0 讨论(0)
  • 2021-01-26 13:36

    You need to change your controller. In the respond_to part you need to add json rendering. Like this:

    respond_to do |format|
         format.json { render :json => @instancevar }
         ....
         ...
         ..
    end
    

    Then you can simply add .json to your url and you will receive the data formated as json. What you might need to do is disabeling the JSON root hich is automaticly added by default. Just add this line to your environment (development.rb, production.rb,...) configuration:

    config.active_record.include_root_in_json = false
    

    This is important when you are parsing the json.

    0 讨论(0)
提交回复
热议问题