2012-08-07 19 views
1

我正在使用STI和Rails 3.2應用程序。我想強制Rails在link_to幫助程序(或任何其他地方生成路徑時)使用超類名稱,而不是子類名稱。如何在使用STI時強制Rails在link_to助手中使用超類名稱?

因此,<%= link_to current_user.name, current_user %>產生/:class_name/:id(類名稱可以是「主持人」,「成員」等等)。

我希望它產生/users/:id,其中users不會更改爲子類的名稱。我知道我可以將current_user更改爲user_path(current_user),但我更願意使用快捷鍵,讓Rails弄清楚。

這可能嗎?

回答

2

我想你應該定義URL傭工,像這樣

def moderator_url record 
    user_url record 
end 

或者只是使用別名

alias :moderator_url :user_url 

這是代碼軌道,當你傳遞一個記錄作爲一個選項,使用URL生成

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

+0

+1我試試看!謝謝! – Mohamad 2012-08-08 01:42:26

+0

在'alias'中找不到任何東西......你能指點我什麼嗎? – Mohamad 2012-08-08 01:45:56

+0

http://ruby.about.com/od/rubyfeatures/a/aliasing.htm – 2012-08-08 07:51:49

0

對於鏈接,我可以得到在此通過添加資源:

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

對於窗體,我需要指定通用窗體。我最初的形式是

= simple_form_for @user do |f| 

爲了使這項工作,我必須指定的路徑和方法,而使用通用名稱,而不是通過用戶對象,以直接的形式:

= simple_form_for :user, url: user_path(@user) do |f| 
+0

但這不是答案你的問題。只要閱讀rails的源代碼,看看我的回答 – 2012-08-07 20:58:58

0

使用命名路線:

<%= link_to current_user.name, user_path(current_user) %> 
+0

我在我的問題中說過我不想使用命名路由。 – Mohamad 2012-08-07 20:04:50