Read more

Render a view from a model in Rails

Henning Koch
August 19, 2013Software engineer at makandra GmbH

In Rails 5 Show archive.org snapshot you can say:

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

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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):

ApplicationController.renderer.defaults # =>
{
  http_host: 'example.org',
  https:      false,
  ...
}
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:

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 Show archive.org snapshot . You can also backport the rails 5 new renderer Show archive.org snapshot

Use case

Posted by Henning Koch to makandra dev (2013-08-19 10:11)