Polyorphic_path does not create the correct path

I am trying to use a rails method named polymorphic_path but I am getting the wrong url. My polymorphic association is with Students and Owners who are Users through the user interface.

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 named current_user that contains a User object. Next line:

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

      

gives me the url "users / 22" instead of returning the student / renter url.

Here is my route.rb file if that helps.

resources :users
resources :students
resources :landlords

      

Where am I going wrong? Thank!

0


source to share


2 answers


OK I understood! And the decision was painfully obvious ...



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

      

0


source


Hmm, not sure if polymorphic_path is supposed to work the way you use it, homemade 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 a few extra lines, you can extend it and work with methods other than just showing.

0


source







All Articles