2

I'm using STI with a Rails 3.2 app. I want to force Rails to use the superclass name in link_to helpers (or any where else when it's generating paths) and not the subclass name.

So, <%= link_to current_user.name, current_user %> produces /:class_name/:id (class name can be "Moderator," "Member," etc...).

I would like it to produce /users/:id, where users does not change to the name of the subclass. I know I can change current_user to user_path(current_user), but I prefer to use the shortcut, letting Rails figure it out.

Is this possible?

Mohamad
  • 34,731
  • 32
  • 140
  • 219

3 Answers3

2

I think you should define url helpers, something like this

def moderator_url record
  user_url record
end

Or just use aliases

alias :moderator_url :user_url

This is code which rails use for url generation when you pass a record as a option

https://github.com/rails/rails/blob/537ede912895d421b24acfcbc86daf08f8f22157/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb#L90

Yuri Barbashov
  • 5,407
  • 1
  • 24
  • 20
  • Can't find anything in `alias` ... can you point me to anything? – Mohamad Aug 08 '12 at 01:45
  • I honestly don't see the need to alias at this point. Why bother when `resources :owners, path: 'users', controller: 'users'` solves the problem? – Mohamad Aug 08 '12 at 11:36
  • Because this is answer to you question, how to avoid using helpers directly. And why `owners`? Why not `resources :users`? – Yuri Barbashov Aug 08 '12 at 18:36
  • There is [a more complete answer here](http://stackoverflow.com/questions/4507149/best-practices-to-handle-routes-for-sti-subclasses-in-rails) – eloyesp Oct 30 '12 at 21:03
0

For links, I can get around this by adding a resource:

resources :owners, path: 'users', controller: 'users'

For forms, I need to specify generic form. My initial form was

= simple_form_for @user do |f|

To make this work, I had to specify the path and the method, while using a generic name instead of passing the user object to the form directly:

= simple_form_for :user, url: user_path(@user) do |f|
Mohamad
  • 34,731
  • 32
  • 140
  • 219
0

Use the named route:

<%= link_to current_user.name, user_path(current_user) %>
aceofspades
  • 7,568
  • 1
  • 35
  • 48