Forum: Ruby on Rails Re: If-Else Conditionals in Views

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6f94c45fd92acbb3e21c328f6b35298a?d=identicon&s=25 Bradley Mazurek (Guest)
on 2006-04-09 08:59
(Received via mailing list)
> I find myself doing the following quite a lot:
>
> <% if user %><%= user.name %><% else %>Anonymous<% end %>
>
> Is there any simpler way to handle the else?  This is a simple example
> so it's not really an issue.. but for more complicated tests this gets
> quite tedious.

For me, I moved the whole thing into a helper.

Because usernames are a potential relationship that I may want to give
more information on, I created a helper that did this, parameterized
by the user object.

In the simple case, it does what you show.  In other cases it will
return a link to the user's information.  If the user is the favorite
of the current user, it may throw in a span tag so that I can colour
the link differently, or include a small inline image.

In my view, I'll have something like:
  <%= render_username post.author %>

Keeps the view clean, and still provides the flexibility I want, plus
it keeps things nice and DRY.

Brad
--
Bradley Mazurek
This topic is locked and can not be replied to.