Rails: Get path / url without knowing the object's class (sitemap for multiple models)

2.8k views Asked by At

I am trying to get the URL or path to a resource without knowing of which class it is. My app has many resources that render pages - think Country, City and so on - and specifically, I want to create a Sitemap. I'd rather build it myself at this stage than using a gem.

I have looked at this tutorial http://aspiringwebdev.com/sitemaps-in-rails-in-five-minutes/ . The author simply creates a route and controller, and then passes an instance variable which he cycles through in the XML view.

In ERB, It looks like this:

<% @countries.each do |entry| %>
  <url>
    <loc>http://yourdomain.com<%= country_path(entry) %></loc>
    <priority>0.7</priority>
  </url>
<% end %>

There are 5 or 6 models I would like to process like this. Preferably, I would do this in the controller:

@entries = [Country.all, City.all, OtherModel1.all, OtherModel2.all]

... then do the each loop on this one instance variable @entries. But I don't know what to use instead of country_path(...), city_path(...) and so on.

Who can help?

1

There are 1 answers

2
fbelanger On BEST ANSWER

Try using the polymorphic_path helper:

Polymorphic URL helpers are methods for smart resolution to a named route call when given an Active Record model instance.

<% @entries.each do |entry| %>
  <url>
    <loc>http://yourdomain.com<%= polymorphic_path(entry) %></loc>
    <priority>0.7</priority>
  </url>
<% end %>

http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html