ruby-on-railsrubyerblink-toruby-on-rails-7

rails helpers string interpolation in erb template


I am using the ternary operator for single-line conditions, with erb printing tag <%= %>

<p>Status:
     <%= notification.read? ? "Read" : link_to "Mark as Read", "/" %>
</p>

I need to give a mark as read link in false condition, in the above scenario getting the syntax template error, here notification is an object of the Notification model.

I want output as-

mark as read 

mark as read would be link.

thanks!


Solution

  • Don't use a ternary:

    <% if notification.read? %>
      Read
    <% else %>
      <%= link_to 'Mark as Read', '/' %>
    <% end %>
    

    Or use parentheses in the link_to method call:

    <%= notification.read? ? 'Read' : link_to('Mark as Read', '/') %>
    

    Remember that anything inside <%= ... %> is just Ruby and that link_to is just a Ruby method like any other.