polymorphic_path not generating correct path

瘦欲@ 提交于 2019-12-12 04:35:18

问题


I am trying to user a rails method called polymorphic_path but I am getting the wrong url. 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. The following line:

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

gives me the url "users/22" instead of returning the Student/Landlord url.

Here is my routes.rb file if that helps..

resources :users
resources :students
resources :landlords

Where am I going wrong? Thanks!


回答1:


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) %>



回答2:


Hmm, not sure if polymorphic_path should work they way You using it, home brewed alternative

# 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.



来源:https://stackoverflow.com/questions/19343535/polymorphic-path-not-generating-correct-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!