title: Rails rendering json partial in model
body: <p>In our rails 3.2 app, we are using Jbuilder to render our json responses (nothing special here). The json view could be as simple as this:</p>
  
  <p>_model_name.json.jbuilder</p>
  
  <pre><code>json.extract!(page, :id, :name, :url_name)
  </code></pre>
  
  <p>We often need to return a deeply nested json object, and Jbuilder partials work great for this:</p>
  
  <p>_page.json.jbuilder</p>
  
  <pre><code>json.extract!(page, :id, :name, :url_name)
  json.page_images (page_images) do |json, page_image|
      json.partial! page_image
  end
  </code></pre>
  
  <p>The last example will retrieve the page, and nested page_images, json representation... again nothing special.</p>
  
  <p>Often, a single partial will call another, and may return a nested json object 2 or 3 levels deep.</p>
  
  <p><strong>PROBLEM</strong></p>
  
  <p>Like I mentioned above, we use Jbuilder partials to quickly link multiple partials together to form a deeply nested json object for the view. We also need build these exact same nested objects as a hash (rather than json) AND make them available to a model.</p>
  
  <p>It's simple to get a Jbuilder object to output a hash using the .attributes! method, but we're having some serious difficultes giving Jbuilder access to the view partials from a model.</p>
  
  <p>Looking at the Jbuilder source, it looks like the JbuilderTemplate class needs access to the controller context to make everything work.</p>
  
  <p>We might try something like this:</p>
  
  <pre><code>class SomeClass
  
    def initialize pages
      @pages = pages
      @context = ActionController::Base.new
    end
  
    def to_hash
       builder = JbuilderTemplate.new(@context)
       builder.pages(@pages) do |json, page|
          json.partial! page
       end
       builder.attributes!
    end
  end
  </code></pre>
  
  <p>The example above is obviously incorrect, but it illustrates what needs to be done. I'm just not sure how to pass initialize a controller from a model, and then pass the controller context.</p>
  
  <p>Some leads that we are following:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/6318959/rails-how-to-render-a-view-partial-in-a-model">how-to-render-a-view-partial-in-a-model</a></li>
  <li><a href="http://wholemeal.co.nz/blog/2011/04/05/rendering-from-a-model-in-rails-3/" rel="nofollow noreferrer">rendering-from-a-model-in-rails-3</a></li>
  </ul>
  
  <p>Can anyone help point us in the right direction?</p>