I'm using Rails 4.0.3. How do I render a partial from the Rails console?
Asked
Active
Viewed 1.8k times
22
-
1possible duplicate of [How do I call controller/view methods from the console in Rails?](http://stackoverflow.com/questions/151030/how-do-i-call-controller-view-methods-from-the-console-in-rails) – Feb 27 '14 at 19:50
-
Check out this previous SO post: http://stackoverflow.com/questions/8538798/rendering-a-partial-from-a-ruby-script-or-console – cat3045 Feb 27 '14 at 20:11
-
2@GraemeMcLean None of those answers are about `#render`. – Chloe Feb 28 '14 at 03:17
3 Answers
42
Try this (in the console):
# initial setup
view_paths = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
av_helper = ActionView::Base.new view_paths
# (Optional) include this if your partial uses route helpers:
include Rails.application.routes.url_helpers
av_helper.render "path/to/your/partial"
Also, for templates:
av_helper.render :template => "path/to/your/template"
Update: The OP reported the partial rendering line did not work, and generated an error. I didn't encounter that, but if others do, this is the version the OP indicated was successful:
av_helper.render :partial => 'tags/tag', :collection => Tag.limit(3)
As Josh Diehl pointed out, you can also use the usual options like locals
in the render. I would expect you should be able to use all the usual render options normally used in controllers and views.
Josh's example:
av_helper.render(partial: "tags/tag", locals: {term: term})

Paul Richter
- 10,908
- 10
- 52
- 85
-
1With locals: `av_helper.render(partial: "tags/tag", locals: {term: term})` – Josh Diehl Sep 26 '14 at 17:56
-
Cool, thanks @JoshDiehl, makes sense. I would expect all the usual render options to work. I'll add that to the answer. – Paul Richter Sep 26 '14 at 22:22
-
Any way to make instance variables available as are commonly used in Rails views? – justingordon Aug 02 '15 at 20:46
-
@justingordon I don't know why I didn't catch your question earlier, sorry for the delay. You could pass them via the `locals` key like described above; you can convert your object's instance variables to a hash like described [here](http://stackoverflow.com/a/8417341/877472), which is similar to how [Rails passes controller instance variables](http://stackoverflow.com/a/18855824/877472). – Paul Richter Apr 21 '16 at 13:36
29
There is an official way to do this in Rails 5 (cf this pull request):
ApplicationController.render 'templates/name'
The developer also made a gem to support this in Rails 4: backport_new_renderer

morgant
- 2,135
- 2
- 19
- 28

Nicolas Maloeuvre
- 3,069
- 24
- 42
13
For me the best way to get it working in Rails 4.2 was with this twoliner:
view = ActionView::Base.new('app/views/products', {}, ActionController::Base.new)
output = view.render(file: 'index.html', locals: {:@products => Product.all})
I found this solution on github.

Fabian
- 275
- 4
- 8