Rails snippet: Rendering a view from model!

Sometimes it comes in handy to render a template from another place than a
controller in Rails. For example using
WickedPdf to generated some pdfs
inside a model comes in quite handy. Normally you need to setup a lot of stuff
for WickedPdf but since everything is already done when calling the build in
render, we can just reuse this.

https://gist.github.com/sideshowcoder/5009089.js

So to call render from somewhere besides a controller, well we need a
controller and we can just call render from there, what pops out is the
actually rendered template as a string (that’s why we call render_to_string of
course), which we can now ship of to wherever we need it.

Enjoy

UPDATE: As Fladam Orin points out in the comments this falls flat if you use helpers like url_for since the controller lacks a request object. This is a problem which can be solved by using an ActionView and loading the helpers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s