views:

81

answers:

6

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?

+1  A: 

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
Mark Rushakoff
+2  A: 

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.

Ryan Bigg
I'm certainly not a fan of unless with an else. What about using `if group.employees.present?`. Calling #present? on an empty array in console appears to return false.
dylanfm
@dylanfm: You make a great point and I've updated the answer to show this.
Ryan Bigg
+1  A: 

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

Omar Qureshi
+1  A: 

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 %>
Tumtu
A: 

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.

kentor
A: 

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