use*_*052 11 ruby templates rendering ruby-on-rails ruby-on-rails-3
我正在运行Ruby on Rails 3,我想渲染一个show.html.erb传递局部变量的template().
在RAILS_ROOT/views/users/show.html.erb我有
Name: <%= @user.name %>
Surname: <%= @user.surname %>
我也有一个页面控制器来处理页面中和application_controller.rb的istance @current_user.一个页面被调用user,所以RAILS_ROOT/views/pages/user.html.erb我有
<%= render :template => "users/show", :locals => { :user => @current_user } %>
上面的代码不起作用(我得到这个错误RuntimeError in Pages#user, Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id:)但这有效:
<%= render :template => "users/show", :locals => { :user => @user = @current_user } %>
我认为这不是 "覆盖" @user变量的好方法.这是因为,例如,如果我需要@user在上面的'render'语句之后回忆起它将不再起作用.
那么,什么是渲染的解决方案show.html.erb?
我也尝试过
<%= render :template => "users/show", :locals => { @user => @current_user } %>
<%= render :template => "users/show", :locals => { :object => @current_user, :as => @user }
但那些不起作用.
UPDATE
如果在pages_controller.rb我这个
def user
  @user ||= @current_user
end
它将工作,并在您可以使用的视图文件中
<%= render :template => "users/show" %>
无论如何,我发现我有这个错误(更多信息见下文):
ActionController::RoutingError in Pages#user
No route matches {:action=>"destroy", :controller=>"users"}
该错误是从位于部分加载的此表单语句生成的show.html.erb:
<%= form_for(@user, :url => user_path) do |f| %>
  ...
<% end %>
Nik*_*bak 22
:locals => { :user => @current_user }
并在模板中
Name: <%= user.name %>
局部变量是本地变量,因此您无需@引用它们.
@ user502052
 
您可以从控制器显式呈现视图.
render :template => "users/show", :locals => {...}
当您不在render控制器中执行时,框架会使用默认参数为您执行此操作.当你这样做时,你可以指定不同的模板文件,传递局部变量,渲染局部:任何render函数支持.
以防万一您不渲染部分,并且不想使用 :template 选项,这也可以在 Rails 4 中完成:
render 'users/show', {user: @current_user}
| 归档时间: | 
 | 
| 查看次数: | 28962 次 | 
| 最近记录: |