0

I have my code as below

<% reported_type = 4 %>
<%=
  if reported_type == 1
    link_to "1 is true", true_path
  else
    link_to "1 is false", false_path
  end

  if reported_type == 2
    link_to "2 is true", true_path
  else
    link_to "2 is false", false_path
  end

  if reported_type == 3
    link_to "3 is true", true_path
  else
    link_to "3 is false", false_path
  end
%>

Expected Output: 1 is false2 is false3 is false

But actual output is 3 is false

When I comment out the third if ... else block, I get 2 is false. If it is because of <%= ... %>, then no if statement must be rendered, right?

As I am new to Rails, I can't figure out why only the last if statement is rendered. If I mix <%= ... %> and <% .. %>, my code will not look nice (As I require every block to be executed). Please help me out.

PrathapB
  • 382
  • 1
  • 4
  • 15

4 Answers4

1

This is not how you do it in rails. It would be enough to wrap each if in its individual <%= as @potashin suggests, but it still would be very unidiomatic. Here's how it should be done:

<% if reported_type == 1 %>
  <%= link_to "1 is true", true_path %>
<% else %>
  <%=  link_to "1 is false", false_path %>
<% end %>

Quite cluttered, I know. That's why people like to use other template languages like HAML:

- if reported_type == 1
  = link_to "1 is true", true_path
- else
  = link_to "1 is false", false_path

To answer your direct question

I can't figure out why only the last if statement is rendered

That's how ruby works. Return value of a block of code is the last expression evaluated in that block. Which you already observed.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
0

You should provide output <%= for each separate if, now it just renders the last helper output. Or something like this:

<%(1..3).each do |x| %>
  <%= (reported_type == x) ? (link_to "#{x} is true", true_path) : (link_to "#{x} is false", false_path)%>
<% end %>
potashin
  • 44,205
  • 11
  • 83
  • 107
0

This does not work because the entire expression within <%= ... %> evaluates to the value of the last if-else-block:

if reported_type == 3
  link_to "3 is true", true_path
else
  link_to "3 is false", false_path
end

To fix this use separate <%= ... %> invocations to wrap each of your if-else blocks.

lorefnon
  • 12,875
  • 6
  • 61
  • 93
0

You are using the ERB templating language inside your views. Please consult this resource

As for your code, try the following:

<% reported_type = 4 %>

<% if reported_type == 1 %>
    <%= link_to "1 is true", true_path %>
<% else %>
    <%= link_to "1 is false", false_path %>
<% end %>

<% if reported_type == 2 %>
   <%= link_to "2 is true", true_path %>
<% else %>
   <%= link_to "2 is false", false_path %>
<% end %>

...

And refer to this answer for correct usage of erb brackets.

Community
  • 1
  • 1
twist900
  • 33
  • 1
  • 6