Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails way to check for object existence before display

I want to find a nice way to check my objects before i display them in the view so I wont get errors.

This is my controler

 @user = User.find_by_username(params[:username])
 @profile = @user.profile 
 @questions = @user.questions

and this is my view

 <% unless @profile.blank? %><%= link_to 'Edit Profile', :controller => 'profiles', :action => 'edit' %><% end %>


     <% unless @user.blank? %>
        Username:<%= @user.username %><br />
    Member Since:<%= @user.created_at.strftime("%d %B %Y")  %><br />
    <% end %>

  <% unless @profile.blank? %>
    First Name: <%= @profile.first_name %><br />
    Last Name: <%= @profile.last_name %><br /><br />
    About: <%= @profile.body %><br /><br />
    Location: <%= @profile.location %><br />
    Birthday: <%= @profile.birthday.strftime("%d %B %Y") %><br />
    <% end %>

As you can see, I'm using more than one checking of each kind ( check unless @profile.blank? ) and I think there will be a better way to do that.

Is there any Rails way to do something smarter than the one I've come up with ?

like image 224
Sharethefun Avatar asked Sep 25 '10 19:09

Sharethefun


1 Answers

Also

<%= if @object.present? %>

looks much simplier for me than

<%= unless @object.blank? %>

especially when we have more than one conditional statement (&& \ || \ and \ or).

api.rubyonrails.org

like image 125
jibiel Avatar answered Sep 28 '22 06:09

jibiel