3

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?

John Topley
  • 113,588
  • 46
  • 195
  • 237
Sam
  • 864
  • 2
  • 11
  • 21

2 Answers2

2

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!

John Topley
  • 113,588
  • 46
  • 195
  • 237
Ole Spaarmann
  • 15,845
  • 27
  • 98
  • 160
  • 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 Jun 03 '09 at 15:21
  • 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 people map.resources companies map.resources contacts That should do the trick! – Ole Spaarmann Jun 03 '09 at 17:10
  • 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 Jun 04 '09 at 00:43
  • 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 Spaarmann Jun 06 '09 at 21:23
-3
<% 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

Tarscher
  • 1,923
  • 1
  • 22
  • 45