我正在使用Active Admin。目前,我有一个索引页面,允许我查看用户已标记的所有资源。鉴于存在各种类型的资源,我的Flagged类和各种资源表之间存在多态关系。
在我的索引页面上,在Active Admin上,我希望能够链接到属于特定资源类型的相应显示页面。
我已经获得了所有代码,但我不喜欢我提出的解决方案。
如何改进现有的解决方案,以便我不必写出尴尬的条件?
模型
class Flag < ActiveRecord::Base
#create relationships with user and flag model
belongs_to :flaggable, polymorphic: true
end
class MilitaryResource < ActiveRecord::Base
has_many :flags, as: :flaggable, :dependent => :destroy
end
class DistrictResource < ActiveRecord::Base
has_many :flags, as: :flaggable, :dependent => :destroy
end
class SchoolResource < ActiveRecord::Base
has_many :flags, as: :flaggable, :dependent => :destroy
end
ActiveAdmin
ActiveAdmin.register Flag do
#parameters permitted to create military resources
permit_params :id, :user_id, :flaggable_id, :flaggable_type, :message, :created_at
#index page
index do
column :flaggable_type
###Current Solution
column "Flagged Resource" do |site|
if site.flaggable_type == "MilitaryResource"
link_to site.flaggable.name, :controller => "military_resources", :action => "show", :id => "#{site.flaggable_id}".html_safe
elsif site.flaggable_type == "SchoolResource"
link_to site.flaggable.name, :controller => "school_resources", :action => "show", :id => "#{site.flaggable_id}".html_safe
elsif site.flaggable_type == "DistrictResource"
link_to site.flaggable.name, :controller => "district_resources", :action => "show", :id => "#{site.flaggable_id}".html_safe
end
end
column :message
actions
end
答案 0 :(得分:4)
你可以这样做以避免条件:
column "Flagged Resource" do |site|
link_to site.flaggable.name,
:controller => site.flaggable_type.underscore.pluralize,
:action => "show",
:id => "#{site.flaggable_id}"
.html_safe
end