views:

369

answers:

2

I have single table inheritance working just fine for my app. I have two user subtypes (Athlete and Company) that inherit the super-type User.

Let's say I am listing all users, and want a link to each user's profile from this list. I want to link to the athletes controller if the type is athlete and the companies controller if the type is company. Is there a standard Rails way to this? Maybe some routing tricks?

A: 
<% User.find(:all).each do |user| %>
  <%= link_to "user", eval("#{user.type.underscore}_path(user)") %>
<% end %>

This will generate a path according to the type of the user (stored in type field). Don't forget to add the type of users to your routes configuration.

I hope this helps.

regards, Stijn

Tarscher
+1  A: 

you can even do that much simpler, Rails recognizes which type of user it has to deal with, so let's say you have the instance variable @user wich can either be an Athlete or a Company, you can just do that

= link_to "Profile", @user

BAM! Rails magic!

ole_berlin
do i have to have my routes set up in a special way to do this? I get an error: undefined method 'user_path'. Can i call the link something else?
Sam
u have to add map.resources for every resource. I had once companies and people which both are contacts, So I had in my routes.rb: map.resources peoplemap.resources companiesmap.resources contactsThat should do the trick!
ole_berlin
one problem i have with this though, i dont want to use the normal show/:id scheme that map.resource sets up. Instead i want something like `home/:permalink`. I was using `map.connect 'athletes/:action/:permalink', :controller => 'athletes', :action => 'home'`
Sam
Then you should go for Tarscher's solution. But check your routing, it doesn't make sense to tell rails that the action is in the url (via athletes/:action) and then set the action to "home"
ole_berlin