You need to create a delegate method on your
team.name unless team.nil?
Then it's just a simple:
<%= @person.team_name %>
If you have a lot of these, consider using the Delegate module:
delegate :name, :ranking, :jersey, :grounds,
:to => :team, :allow_nil => true, :prefix => true
# Person now responds to #team_name, #team_ranking, #team_jersey, #team_grounds as above
The reason this approach works better has to do with the Principle of Least Knowledge:
The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was proposed at Northeastern University towards the end of 1987, and can be succinctly summarized in each of the following ways:
- Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
- Each unit should only talk to its friends; don't talk to strangers.
- Only talk to your immediate friends.
The last bullet point is the key. Your view should only be calling methods on
@person. In order to get the team name, your view should not need to test for the existence of
@person.team. That requires your view to have too much knowledge of the
@person object, and instead it is preferable to create a delegate method in
Person that checks for