I needed to display a html link to an active-record model and a specific action in the respective controller only if a given condition was met. I tried to use the rails link_if helper but it was not suitable because I wanted to perform the test on several alternative conditions leading to several alternative links.
In fact, I was building an audit table listing errors coming from several active-record models. I wanted to jump back from the error in the audit table to the original record in the table producing the error. I had one audit table and 6 different tables where the error could come from. In the audit table I had 2 special fields. The first one representing the original ID from the table producing the error. The second one representing the source of data, i.e. the table producing the error.
The solution:
Using the CASE syntax in RUBY I was able to circumvent the problem which puzzled me for a while.
The correct syntax in the view is the following:
<% case validation.OutputFile when "LIMIT" %> <%= link_to image_tag("icons/application_edit.png") , :controller => 'limits' ,:action => "show", :id => validation.Original_id %> <% when "COUNTERPART" %> <%= link_to image_tag("icons/application_edit.png") , :controller => 'counterparties' ,:action => "show", :id => validation.Original_id %> <% when "PROVISIONS" %> <%= link_to image_tag("icons/application_edit.png") , :controller => 'provisions' ,:action => "show", :id => validation.Original_id %> <% when "NOSTRO" %> <%= link_to image_tag("icons/application_edit.png") , :controller => 'nostros' ,:action => "show", :id => validation.Original_id %> <% when "OTC" %> <%= link_to image_tag("icons/application_edit.png") , :controller => 'derivatives' ,:action => "show", :id => validation.Original_id %> <% when "LOANBOOK" %> <%= link_to image_tag("icons/application_edit.png") , :controller => 'loanbooks' ,:action => "show", :id => validation.Original_id %> <% else %> <%=h "-" %> <% end %>
Where : 'nostros', 'limits', ... are the names of my controllers where I want to perform the action 'Show' on the original id (id in the table producing the error). "OTC","LIMIT","LOANBOOK",... are the values in the field OUTPUFILE in my audit table indicating the source of data producing the error. validation.OutputFile is the value being evaluated in the WHEN condition.
At the end if no condition is met, I have chosen to display '-' instead of the image link. You could also choose not to display anything or a blank value ''.
Simple and efficient.