2013-10-13 83 views
0

我想用戶一個名爲polymorphic_path的rails方法,但我得到了錯誤的url。 我的多態關聯是通過可用的兩個用戶的學生和房東。polymorphic_path不生成正確的路徑

這裏是我的模型:

class User < ActiveRecord::Base 
    belongs_to :userable, polymorphic: true 
end 

class Student < ActiveRecord::Base 
    has_one :user, :as => :userable 
end 

class Landlord < ActiveRecord::Base 
    has_one :user, :as => :userable 
end 

我有一個名爲CURRENT_USER保存用戶對象變量。以下行:

<%= link_to "Profile", polymorphic_path(current_user) %> 

給我的網址「users/22」,而不是返回學生/房東網址。

這裏是我的routes.rb文件是否有幫助..

resources :users 
resources :students 
resources :landlords 

我要去哪裏錯了? 謝謝!

回答

0

好吧,我明白了!而解決方案是痛苦的明顯...

<%= link_to "Profile", polymorphic_path(current_user.userable) %> 
<%= link_to "Edit", edit_polymorphic_path(current_user.userable) %> 
0

嗯,不知道是否應該polymorphic_path他們的方式您可以使用它的工作,自家釀製的替代

# application_controller.rb  
helper_method :current_profile, :path_to_profile 
def current_profile 
    @current_profile ||= current_user.userable 
end 

def path_to_profile 
    send("#{current_profile.class.downcase}_path", current_profile) 
end 

隨着一些額外的線可以擴展它與其他的方法來工作了,不僅展示。

+0

看起來像最優雅的非優雅的解決方案......我只是認爲,這是什麼polymorphic_path的意思。但感謝您的答案。 –