Reputation: 91
In my rails app I have a very dynamic user dashboard that shows and hides div elements based on the users role (customer, employee, admin).
For example: users/show.html.erb
<% if current_user.role_id == 4 %>
<th>Edit</th>
<th>Delete</th>
<% elsif current_user.role_id == 1 %>
<th>Cancel Appointment</th>
<% else %>
<% end %>
</tr>
</thead>
I stored the table nav tabs inside their own partials like this:
<% if current_user.role_id == 1 %>
<%= render 'users/customer_bar' %>
<% elsif current_user.role_id == 2 %>
<%= render 'users/employee_bar' %>
<% elsif current_user.role_id == 4 %>
<%= render 'users/honcho_bar' %>
The same could be done for the aforementioned tags but that would not at all be DRY. Is there a better way? Why is it bad to conditionally format tags in this way?
Upvotes: 3
Views: 717
Reputation: 76784
Statement
Maybe you're looking for case / switch
:
case current_user.role_id
when 4
#do something for 4
when 1
#do something for 1
end
--
System
I would highly recommend using a partial
to get this to work:
<%= render partial: "your_partial", local: { your_local_var: "value" } %>
This will allow you to define the conditions in the partial itself:
#app/views/controller/your_partial.html.erb
<% if var == "value" %>
...
<% else %>
...
<% end %>
Bad?
I wouldn't say it's "bad" for the sake of it - it's typically the case that you'll need conditions. The issue, I think, is you need to ensure you're able to handle the conditions in the most effective way.
Using case / switch
would be a legitimate way of doing this, however, you may have an issue further up the stack
Upvotes: 2