user3224820
user3224820

Reputation: 211

Using link_to with conditions

I'm using the following code to display the name of the contact and link to their message.

<%= link_to message.contact.try(:name), message_path(message) %>

When a contact is deleted from the list, I would like to show a placeholder like "Contact deleted" and link to the message instead of just showing the URL. I tried link_to_if, but it didn't offer the expected output. Is there an effective solution for this?

Upvotes: 0

Views: 95

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176412

You can use link_to_if if the name of the link is the same. You can also use it with a workaround.

<%= link_to_if message.contact, message.contact ? message.contact.name : "Contact deleted", message_path(message) %>

However, I think the cleanest approach is an if.

<% if message.contact %>
  <%= link_to message.contact.name, message_path(message) %>
<% else %>
  Contact deleted
<% end %>

Upvotes: 1

Related Questions