Rails:在不知道对象的class的情况下获取路径/url(多个模型的站点地图)
Rails: Get path / url without knowing the object's class (sitemap for multiple models)
我正在尝试获取资源的 URL 或路径,但不知道它是哪个 class。我的应用程序有许多呈现页面的资源——想想国家、城市等等——具体来说,我想创建一个站点地图。我宁愿在这个阶段自己构建它,也不愿使用 gem.
我看过这个教程http://aspiringwebdev.com/sitemaps-in-rails-in-five-minutes/。作者简单地创建了一个路由和控制器,然后传递了一个他在 XML 视图中循环的实例变量。
在 ERB 中,它看起来像这样:
<% @countries.each do |entry| %>
<url>
<loc>http://yourdomain.com<%= country_path(entry) %></loc>
<priority>0.7</priority>
</url>
<% end %>
有 5 或 6 个模型我想这样处理。我最好在控制器中执行此操作:
@entries = [Country.all, City.all, OtherModel1.all, OtherModel2.all]
... 然后在这个实例变量 @entries
上执行 each
循环。但是我不知道用什么代替country_path(...)
、city_path(...)
等等。
谁能帮忙?
尝试使用 polymorphic_path
助手:
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
我正在尝试获取资源的 URL 或路径,但不知道它是哪个 class。我的应用程序有许多呈现页面的资源——想想国家、城市等等——具体来说,我想创建一个站点地图。我宁愿在这个阶段自己构建它,也不愿使用 gem.
我看过这个教程http://aspiringwebdev.com/sitemaps-in-rails-in-five-minutes/。作者简单地创建了一个路由和控制器,然后传递了一个他在 XML 视图中循环的实例变量。
在 ERB 中,它看起来像这样:
<% @countries.each do |entry| %>
<url>
<loc>http://yourdomain.com<%= country_path(entry) %></loc>
<priority>0.7</priority>
</url>
<% end %>
有 5 或 6 个模型我想这样处理。我最好在控制器中执行此操作:
@entries = [Country.all, City.all, OtherModel1.all, OtherModel2.all]
... 然后在这个实例变量 @entries
上执行 each
循环。但是我不知道用什么代替country_path(...)
、city_path(...)
等等。
谁能帮忙?
尝试使用 polymorphic_path
助手:
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