如何使用case语句来显示部分

时间:2017-05-29 00:19:27

标签: ruby-on-rails

我试图根据模型的值显示部分内容。

<% if @user.new_record? %>
  <%= render partial: "step1", locals: { user: @user } %>
<% else %>
  <%
    case @user.current_step
    when "step2"
      render partial: "step2", locals: { user: @user }
    when "step3"
      render partial: "step3", locals: { user: @user }
    when "step4"
      render partial: "step4", locals: { user: @user }
    end
  %>
<% end %>

我的日志显示正在呈现正确的部分,但我在页面上看不到任何内容。

  Rendering users/new.html.erb within layouts/checkout
  Rendered users/_step2.html.erb (1.9ms) [cache miss]
  Rendered users/new.html.erb within layouts/checkout (4.5ms)

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

您遗漏了=声明中的case

<%=
  case @user.current_step
  when "step2"
    render partial: "step2", locals: { user: @user }
  when "step3"
    render partial: "step3", locals: { user: @user }
  when "step4"
    render partial: "step4", locals: { user: @user }
  end
%>

虽然,如果@user.current_step的内容总是与部分名称相匹配(如您的示例中所示),您可以使用它并跳过case语句,如下所示:

<%= render partial: @user.current_step, locals: { user: @user } %>