我想测试多态子级是否属于父级。
@event.eventable_id == @current_user.id and @event.eventable_type == current_user.class.name
现在,这很丑陋,不应该出现在这样的视图中。但我想对每个多态对象进行此检查。因此,我需要一种元编程方式来找出多态关系表的命名方案。
phone to phonable
social to sociable
etc.
该方法看起来像这样。
if @event.belongs_to(current_user) #<NoMethodError: undefined method `belongs_to' for #<Event:
因此,我需要一个辅助方法来检查多态关系。如果我能得到像这样的任何多态孩子的名字方案
@event.polymorphic_relationship_table_name
然后,我可以将其合并到元编程助手中。如果已经有为此解决方案,请告诉我。
我得到了它!这是获取多态关系名称方案的答案。
@event.class.reflect_on_all_associations(:belongs_to).first.name
=> :eventable # this is the ouput
我可以将任何对象实例放在 .class.reflect_on_all_associations(:belongs_to).first.name
对此最有帮助的文档是Ryan Stenberg撰写的从ActiveRecord :: Base Classes识别外键依赖项。
首先是一个辅助方法。
app / helpers / application_helper.rb
module ApplicationHelper
def child_and_parent?(obj, user)
obj_id = Integer(eval "obj.#{obj.class.reflect_on_all_associations(:belongs_to).first.name}_id")
obj_type = String(eval "obj.#{obj.class.reflect_on_all_associations(:belongs_to).first.name}_type")
(user.id == obj_id) and (user.class.name == obj_type)
end
end
然后在视图中使用它删除不属于当前用户的功能。
app / views / events / index.html.erb和app / views / events / show.html.erb
<% if child_and_parent? @event, current_user %>
<li><%= link_to 'Edit', edit_event_path(@event) %></li>
<li><%= link_to 'Delete', @event, method: :delete, data: { confirm: 'Are you sure?' } %></li>
<% end %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句