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) %>
题
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!
解决方案
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
# 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.