简体   繁体   English

polymorphic_path无法生成正确的路径

[英]polymorphic_path not generating correct path

I am trying to user a rails method called polymorphic_path but I am getting the wrong url. 我正在尝试使用名为polymorphic_path的rails方法,但网址错误。 My polymorphic association is with Students and Landlords who are both Users through userable. 我与学生和房东的多态关联是他们都是用户(通过用户)。

Here are my models: 这是我的模型:

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

I have a variable called current_user holding the User object. 我有一个名为current_user的变量,用于保存User对象。 The following line: 下一行:

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

gives me the url "users/22" instead of returning the Student/Landlord url. 给我的网址是“ users / 22”,而不是返回学生/房东的网址。

Here is my routes.rb file if that helps.. 这是我的routes.rb文件,如果有帮助..

resources :users
resources :students
resources :landlords

Where am I going wrong? 我要去哪里错了? Thanks! 谢谢!

Ok, I got it! 好,我知道了! And the solution was painfully obvious... 痛苦的解决方案显而易见。

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

Hmm, not sure if polymorphic_path should work they way You using it, home brewed alternative 嗯,不确定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

With few additional lines You can extend it to work with other methods too, not only show. 用很少的其他行,您可以扩展它来使其与其他方法一起使用,不仅显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM