Blankman
Blankman

Reputation: 267180

How to use a case statement to display a partial

I'm trying to display a partial based on the value of a model.

<% 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 %>

My logs show that is rendering the correct partial, but I don't see anything on the page.

  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)

What I am doing wrong here?

Upvotes: 0

Views: 225

Answers (1)

Gerry
Gerry

Reputation: 10517

You are missing the = in your case statement:

<%=
  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
%>

Although, if the content of @user.current_step is always going to match the name of the partial (as in your example) you could just use that and skip the case statement, like this:

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

Upvotes: 2

Related Questions