Views and If Else conditions

Hello all,

How do I use nested if conditions in my views? I have something like

if(res.birthdate_status == “0”)
{
if(res.gender == “M” || res.gender==“F”)
print , //print a comma
print res.age
}

Well, you could do this, but I don’t like it:

<% if @user.birthdate_status == 0 %>
<% if @user.gender == “M” || @user.gender == “F” %>

Thanx brian, yeah it does help.
Please also tell me another thing. I have the following in my index.rhtml
<% @result.each do |res| %>
<%= res.first_name %>


<%= res.register.language_speak
%>





<% end %>
My models are as follows
class Profile < ActiveRecord::Base
has_many :friends, :foreign_key => “user_id”
has_one :register, :foreign_key => “id”

def self.table_name() “mhp_profile” end
end
class Friend < ActiveRecord::Base
belongs_to :profile

def self.table_name() “mhp_friends” end
end
class Register < ActiveRecord::Base
belongs_to :profile

def self.table_name() “mhp_register” end
end
But Im getting the following error.
Showing profile/index.rhtml where line #4 raised:

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.language_speak

Any idea what am I doing wrong…I have only one controller for profile as follows

class ProfileController < ApplicationController

def index

@result = Profile.find(:all)

end

end

It sounds like you don't have an associated "register" for this "res". A very simple solution is to test register, such as

<%= res.register.language_speak if res.register %>

or

<%= res.register.language_speak unless res.register.nil? %>

depending on how your mind likes to conceptualize things.

Peace,
Phillip

I'd be tempted to add a method on the profile model to return
language_speak (should this really be something like language_spoken
?).

class Profile
  ...
  def language_speak
      register.language_speak if register
  end
end

and then change the view code to just:

  <%= res.language_speak %>

The original code violates the so-called "law" of Demeter which says
you shouldn't reach through an object to get to another one, the
canonical example of a demeter violation would be having a PaperBoy
object which grabs the Wallet object from one if its Customers to
extract payment for a subscription.

Besides the obvious rudeness, doing this with a method in the model
you have directly at hand isolates the view code from potential future
refactorings.