我希望一个类通过多态关联属于其他类.
限制与特定类列表的关联的最佳方法是什么?
我正在考虑使用这样的自定义验证方法,但我不知道这是否真的是最好的主意:
class Feature < ActiveRecord::Base
belongs_to :featureable, polymorphic: true
validate :featurable_is_of_allowed_class
FEATURABLE_CLASSES = ["Country", "City", "Store", "Product"]
def featurable_is_of_allowed_class
if !FEATURABLE_CLASSES.include? featurable.class.name
errors.add(:featurable, "class not allowed for association")
end
end
end
Run Code Online (Sandbox Code Playgroud) validation activerecord ruby-on-rails polymorphic-associations
我试图获取资源的URL或路径,而不知道它是哪个类.我的应用程序有很多资源可以呈现页面 - 想想国家,城市等等 - 具体来说,我想创建一个站点地图.我宁愿在这个阶段自己构建它而不是使用宝石.
我查看了本教程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 %>
Run Code Online (Sandbox Code Playgroud)
我想要像这样处理5或6个模型.我最好在控制器中执行此操作:
@entries = [Country.all, City.all, OtherModel1.all, OtherModel2.all]
Run Code Online (Sandbox Code Playgroud)
...然后each对这个实例变量进行循环@entries.但我不知道该用什么代替country_path(...),city_path(...)等等.
谁可以帮忙?