ruby on rails - Simple helper method - Am I doing it right? -


new ruby , rails.

i developing simple app can register teams, players etc , looks this:

team has_many players players belongs_to team

when want show player in view(normal users):

<%= @player.name %> - <%= playerteam %> 

and in admin view looks this:

<% @players.each |player| %>     <tr>                 <td><%= player.id %></td>            <td><%= player.name %></td>         <td><%= playerteam(player) %></td>         <td><%= owner(player) %></td>                    </tr> <% end %> 

and helper method:

def playerteam(player = nil)         if player != nil     if player.team_id == nil       return "no team"     else       @team = team.find(player.team_id)       return @team.name     end   else                   if @player.team_id == nil       return "no team"           else       @team = team.find(@player.team_id)       return @team.name      end   end end 

it works not pretty or "ruby sexy"

at first used normal view when wanted use admin-view had add parameter default value , if-clause.

are there better way?

i wouldn't use helper method @ all. helper methods shouldn't used retrieve model data. that's what's model for.

you can this:

normal users:

<%= @player.name %> - <%= player.team ? player.team.name : 'no team' %> 

admin:

<% @players.each |player| %>     <tr>                 <td><%= player.id %></td>            <td><%= player.name %></td>         <td><%= player.team ? player.team.name : 'no team' %></td>         <td><%= owner(player) %></td>                    </tr> <% end %> 

you similar owner-helper

to avoid ? :-if-else syntax in every view can add player model

class player < activerecord::base   def team_name     team ? team.name : "no team"   end end 

then views this:

normal users:

<%= @player.name %> - <%= @player.team_name %> 

admin:

<% @players.each |player| %>     <tr>                 <td><%= player.id %></td>            <td><%= player.name %></td>         <td><%= player.team_name %></td>         <td><%= owner(player) %></td>                    </tr> <% end %> 

imho: more "rails sexy" ;-)


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -