1
votes

I am working with Active Admin. Currently, I have an index page that allows me to view all Resources that have been Flagged by a user. Given that there are various types of resources, I have a polymorphic relationship between my Flagged class and the various Resource Tables.

In my index page, on Active Admin, I would like to be able to link to the appropriate Show page belonging to a particular Resource Type.

I've gotten all my code to work, but I do not like the solution I've come up with.

How I can improve my current solution so I don't have to write up an awkward conditional?

Models

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
1

1 Answers

6
votes

You can do something like this to avoid the conditional:

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