Reputation: 453
In my erb file, I have the following code in the body tag:
<% @tasks.each do |task| %>
<%= task.name %>
<% end %>
This is working, but I only want to display task.name if task.otherAttribute does not equal -1.
For some reason, I can't figure out how to do this! Any tips much would be much appreciated.
Thank you in advance.
Upvotes: 0
Views: 2897
Reputation: 35308
I tend to use #select
and #reject
for this idiom, since that's basically what you're doing.
<%= @tasks.reject{|t| t.other_attribute == -1}.each do |task| %>
<%= task.name %>
<% end %>
These come from the Enumerable module, which most things with an #each
method include.
Upvotes: 3
Reputation: 3919
Try this:
<% @tasks.each do |task| %>
<%= task.name if task.otherAttribute != 1 %>
<% end %>
Or:
<% @tasks.each do |task| %>
<%= task.name unless task.otherAttribute == 1 %>
<% end %>
I will provide some more options for future reference:
<% @tasks.each do |task| %>
<% if task.otherAttribute != 1 %>
<%= task.name %>
<% end %>
<% end %>
<% @tasks.each do |task| %>
<%= task.otherAttribute == 1 ? '' : task.name %>
<% end %>
Good luck!
Upvotes: 3
Reputation: 84373
You can put conditionals into your ERB code.
<%= task.name if task.otherAttribute != 1 %>
You can also perform more complex tasks with a more verbose syntax. It's not necessary in your case, but you could also do more traditional if/else blocks like so:
<% if task.otherAttribute != 1 %>
<%= task.name %>
<% end %>
Upvotes: 0