I am doing the Lynda.com rails tutorial and they explain how to render another view than the default one using render(‘methodname’).
However, I noticed this rendering is not “nested”. For example, in the code below, localhost:3000/demo/index would generate the view in views/demo/hello.html.erb, while localhost:3000/demo/hello would render the text ‘Hello there’.
Is there a way to have “nested” rendering, i.e. such that requesting demo/index would return ‘Hello there’ in this example?
(Also, some use cases for nested rendering would be nice. I am asking only out of curiosity.)
class DemoController < ApplicationController
def index
render ('hello')
end
def hello
render(:text => 'Hello there')
end
end
I don’t know what you exactly mean by nested rendering.
Scenario #1
If you want action “index” to be triggered but template “hello.html.erb” to be shown, you can do
This will render the template
app/views/demos/hello.html.erb(or other format if you want it to (i.e. specify it in the url)).So
render :action => :hellois just a shortcut.You can also do
render :template => "hello.html.erb"orrender :file => Rails.root.join("app/views/demos/hello.html.erb")(sometimes useful).Scenario #2
If you want to render that text, you can just call hello method inside index method
If you don’t want other stuff from hello action to be run you can separate it to other method, like so:
You can not render twice in the same action.
Btw the url should not say
/demos/indexbut just/demos.Index is the default action for
resourcesroute (resources :demos).Please select the scenario which suits you (so I can remove unnecessary text from this answer).