views:

47

answers:

2

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 ?

A: 

How about building empty profile for user before saving it? How about using analogy with exclamation mark which will raise ActiveRecord::RecordNotFound which in turn will display 404 page.

P.S. I'd also recommend trimming controller down to one instance variable.

Eimantas
I just dont want to display the users info ( profile etc ) if the user doesnt have one. How an empty profile would help me to do that ?
ok then - what's the point of creating a user without a profile?
Eimantas
profile is another model. Not everyone has a profile.
+1  A: 

Hi user387221

As I see, there is no way you can skip this @.blank? validation as you dont want to display the records if they are empty but I have few suggestions

1 - Make following sections as partials

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

and

<% 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 %>

it will keep your view cleaner and will give you the flexibility of using them in anyware in your app

2 - take the below line

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

inside the profile display as its more appropriate

cheers

sameera

sameera207