Reputation: 2380
There is a website
attr on product_lead
table which is optional. If it's present then I wanna turn @produc_lead.lead
into a link, but if it's not it should be plain text.
If I use the code below and the website is nil then the link points to the page the user is currently on. If I do it with @product_lead.try(:website)
, it's gonna be the same. But as I mentioned I would like to have plain text over link in this case.
<%= link_to @product_lead.website, target: "_blank" do %>
<%= @product_lead.lead %>
<% end %>
After playing around I fell back to the following solution, but it's terrible. Any better ideas?
<% if @product_lead.website %>
<%= link_to @product_lead.website, target: "_blank" do %>
<%= @product_lead.lead %>
<% end %>
<% else %>
<%= @product_lead.lead %>
<% end %>
Upvotes: 1
Views: 59
Reputation: 1930
Maybe link_to_if if Rails 4
<%= link_to_if(@product_lead.website, @product_lead.lead, @product_lead.website) do %>
@product_lead.lead
<%= end %>
Upvotes: 2
Reputation: 583
Well, link_to
is going to generate a <a>
tag, whether you provide a valid URL or not. So if the URL is nil, yes, it's gonna be a link for you own page.
If you want to "hide" this, you could call a partial in which you place you if/else and so on, but it's just to sweep this under the rug :)
Or if you wanna go further, as @Jovica Šuša, a view helper is the most elegant solution.
Upvotes: 2