2013-10-13 84 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的意思。但感谢您的答案。 –