views:

54

answers:

3

I've got a Ruby on Rails app where I do the following:

@user = User.find(:first, :conditions => ['LOWER(username) = ?', current_subdomain.downcase], :include => :bio)

Where ':include => :bio' is the important part.

Then in the view I want to display some bio:

<em><%= @user.bio.title %></em><br />
<%= @user.bio.city %><br />
<%= @user.bio.state %><br />
<%= @user.bio.country %>

But if the user dosn't have any information it just will turn up a couple of blank rows.

I've tried a couple of different things, none has worked so far...

<% if @user.bio.title %> # is always true
<% if @user.bio.title > 0 %> # triggers an error if @user.bio.title isn't set
<% unless @user.bio.title.empty? %> # same as above

Any sollution to how to just display the data the user has got?

Thanks in advance!

UPDATE

Ok, if figured some things out:

<% if @user.bio.title %> # Works if the bio isn't set at all.
<% if @user.bio.title > 0 %> # Works if the bio is set.

So I can use a sollution that looks like:

<% if @user.bio.title %><% if @user.bio.title > '0' %><%= @user.bio.title %><% end %><% end %>

But it seam a little overkill? Any better suggestions?

Thanks!

A: 

Can you try this?

if defined?(@user.bio.title)
zwip
Seams to always return false when I tried it quickly now: <% if defined?(@user.bio.title) %><%= @user.bio.title %><% end %>
Alfred Nerstu
+3  A: 

Here's one way to think about it. The user has a bio and has filled in the title field. In Ruby:

<% if @user.bio && [email protected]? %> 

If you are going to display multiple fields from the bio you can separate this into 2 checks e.g.

<% if @user.bio %>
  <% unless @user.bio.title.blank? %>
    Title: <%= @user.bio.title %>
  <% end %>
  <% unless @user.bio.other_field.blank? %>
    Other field: <%= @user.bio.other_field %>
  <% end %>
<% end %>

Alternative

Another way is to put methods on your model to provide direct access to the bio fields. e.g.

# return the user's title or nil if no bio
def title
  bio.title if bio
end

Then in your view you can just do:

<% unless @user.title.blank? %>
  Title: <%= @user.title %>
<% end %>
mikej
That works! Better than dubble if's for sure, thanks!
Alfred Nerstu
I like the alternative here, pull the view code out into a model code.
Jason Noble
A: 

Maybe you can check out object.try or andand?

Ed