I am running Ruby on Rails 3 and I would like to render a template (show.html.erb
) passing a local variable.
In RAILS_ROOT/views/users/show.html.erb
I have
Name: <%= @user.name %>
Surname: <%= @user.surname %>
I have also a page controller to handle pages and in the application_controller.rb
an istance of @current_user
. A page is called user
, so in RAILS_ROOT/views/pages/user.html.erb
I have
<%= render :template => "users/show", :locals => { :user => @current_user } %>
The above code doesn't work (I get this error: RuntimeError in Pages#user, Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
) but this works:
<%= render :template => "users/show", :locals => { :user => @user = @current_user } %>
I think it is not a good approach to "overwrite" the @user
variable. This is because, for example, if I need to recall @user
after the above 'render' statement it will don't work anymore.
So, what is a solution in order to render show.html.erb
?
I tryed also
<%= render :template => "users/show", :locals => { @user => @current_user } %>
<%= render :template => "users/show", :locals => { :object => @current_user, :as => @user }
but those don't work.
UPDATE
If in pages_controller.rb
I put this
def user
@user ||= @current_user
end
it will work and in the view files you can just use
<%= render :template => "users/show" %>
Anyway, I discoverd that I have this error (see below for more info):
ActionController::RoutingError in Pages#user
No route matches {:action=>"destroy", :controller=>"users"}
The error is generated from this form statement located in a partial loaded from show.html.erb
:
<%= form_for(@user, :url => user_path) do |f| %>
...
<% end %>
:locals => { :user => @current_user }
and in template
Name: <%= user.name %>
Local variables are local, so you don't need @
to refer them.
@user502052
You can render view explicitly from your controller.
render :template => "users/show", :locals => {...}
When you don't execute render
in controller, framework does that for you with default parameters. When you do, you can specify different template file, pass local variables, render a partial: anything render
function supports.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With