Posted about 4 years ago. Visible to the public.

Render a view from a model in Rails

In Rails 5 you can say:

Copy
ApplicationController.render( :template => 'users/index', :layout => 'my_layout', :assigns => { users: @users } )

If a Request Environment is needed you can set attributes default attributes or initialize a new renderer in an explicit way (e.g. if you want to use users_url in the template):

Copy
ApplicationController.renderer.defaults # => { http_host: 'example.org', https: false, ... }
Copy
renderer = ApplicationController.renderer.new( http_host: 'example.org', https: false ) renderer.render( :template => 'users/index', :layout => 'my_layout', :assigns => { users: @users } )

In Rails 3 and 4 you can say:

Copy
ApplicationController.new.render_to_string( :template => 'users/index', :layout => 'my_layout', :locals => { :@users => @users } )

Mind the weird syntax to set @ variables in :locals.

Hat tip to BitCrowd. You can also backport the rails 5 new renderer

Use case

  • Render pdfs with e.g. pdfkit from html to attach to an email or a model
  • Generate slow reports async

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Author of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandropedia