Passing local variables to a view from controller
Passing Data from the Controller to the View
Here's a NovelController class, to be put into app/ controllers/novel_controller.rb.
class NovelController < ApplicationController def index @title = 'Shattered View: A Novel on Rails' endend
Since this is the Novel controller and the index action, the corresponding view is in app/views/novel/index.html.erb
<h1><%= @title %></h1>
Output:
Shattered View: A Novel on Rails
The view is interpreted after NovelController#index
is run. Here's what the view can and can't access:
- It can access the instance variables
@title
, because they've been defined on theNovelController
object by the timeNovelController#index
finishes running. - It can call instance methods of the instance variables
@title
.
I think it should be like
render 'books/show', :locals => {:resource => 'Some text'}
It works for me
First I am wondering why would you need the template:
. Are you on Rails 2.x? If not, then the :template
option is no longer required. You should be able to get along fine with just
render "books/show"
Second do you need to specify the template? What is the controller you want to render from? If that's BooksController
, then you don't need the template path either, which makes the line being just
render
That's without the variables yet. Now, I just checked, and a simple:
render locals: { resource: "Some text" }
as well as:
render 'books/show', locals: { resource: "Some text" }
works for me just fine. Maybe earlier Rails versions treated 'resource' as some kind of a keyword? Don't know, but the above Worksformeâ„¢ in both forms.