1

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?

6 Answers 6

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: You make a great point and I've updated the answer to show this.
2

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

Comments

1

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

Comments

1

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

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.