Patrick
Patrick

Reputation: 475

rails way of doing if/else logic

I have following code which seems to work fine:

  <%if group.employees.count > 0%>
    <td><%= link_to group.employees.count.to_s, {:action => 'index', :controller => 'employees'}, {:id=>group.id}%></td>
  <%else%>
    <td><%= link_to "Add Employee", {:action => 'new', :controller => 'employees'}%></td>        
  <%end%>

I'm just wondering how this can be written in more rails friendly way using unless?

Upvotes: 1

Views: 1069

Answers (6)

VvDPzZ
VvDPzZ

Reputation: 3095

You can use helper and content_tag to generate html instead of ugly erb grammar.

def foo
   if group.employees.count > 0
      content_tag(...)
   else
      content_tag(...)
   end
end

then in your view

<%= foo %>

Upvotes: 1

BitOfUniverse
BitOfUniverse

Reputation: 6021

You can try this way:

<% if group.employees.any? %>
 <td><%= link_to group.employees.count, employees_path, { :id=> dom_id(group) } %></td>
<% else %>
  <td><%= link_to "Add Employee", new_employee_path %></td>        
<% end %>

Upvotes: 1

Ryan Bigg
Ryan Bigg

Reputation: 107728

I would (with dylanfm's advice in the comment underneath) write it like this:

<% if group.employees.present? %>
  <td><%= link_to group.employees.count.to_s, employees_path, { :id=> "group_#{group.id}" }%></td>
<% else %>
  <td><%= link_to "Add Employee", new_employee_path %></td>        
<% end %>

Here I've used the employees_path and new_employee_path methods which are generated by using the routing helpers in config/routes.rb. You can read more about routing by reading the Routing from the Outside In guide.

Upvotes: 5

kentor
kentor

Reputation: 1144

Tumtu's way is the best, but I would even put the td tags outside the if statements. I would never use unless with else, and certainly is not a "rails way" to use unless.

Upvotes: 0

Omar Qureshi
Omar Qureshi

Reputation: 9103

I consider it unreadable to use unless with else. Would be better to stick with what you have.

Upvotes: 2

Mark Rushakoff
Mark Rushakoff

Reputation: 258478

You have an if-else branch (two possible different outcomes), so using unless would require you to change it to an unless-else branch, which is hard to understand. If-else is the way to go in this situation.

If you only had a single condition, i.e.

if foo != 0
   do_something(bar)
end

It could be rewritten as

do_something(bar) unless foo == 0

Upvotes: 1

Related Questions