0

I have an ActiveAdmin resource whose collection requires some particularly complex queries to avoid a bunch of n+1's. I tried to modify controller#scoped_collection with all the proper .includes or .joins, but it was still doing n+1's.

I've since changed to an approach of just doing the queries by hand and dumping the relevant results into Hashes. Then in my index view, I grab the data from the hashes, rather than from the scoped_collection.

Unfortunately, I can't figure out how to make an instance variable available in the index scope. I got around that by putting it into the params hash (which is available in the index scope), but that ends up breaking the filtering.

So, is there some way I'm not seeing to scope variables from inside scoped_collection or some other sort of before_filter-like method that will be available inside index?

Sample code:

ActiveAdmin.register ComplexResource do
  actions :index

  controller do
    def scoped_collection
      @complex_collection_relation = ComplexResource.where(crazy: :stuff)

      # a bunch more lines of code to do avoid n+1's and put info into supporting data hash

      @supporting_data_hash = {}
      complex_collection_relation.each{|r| supporting_data_hash[r.id] = stuff }

      # my hacky workaround because @supporting_data_hash isn't available below
      params[:supporting_data_hash] = @supporting_data_hash

      return @complex_collection_relation
    end
  end

  filter :my_filter_that_gets_broken, as: :string

  index do
    column :name
    column :complex_attribute_1 do |r|
      params[:supporting_data_hash][r.id][:complex_attribute_1]
    end
    # how can I do something like this without using the params workaround
    # column :complex_attribute_1 do |r|
    #   @supporting_data_hash[r.id][:complex_attribute_1]
    # end
  end

end
LikeMaBell
  • 1,529
  • 2
  • 13
  • 24

2 Answers2

3

I know this is an old question but it's the first one that comes up when googling. Also, I'm not 100% sure it applies to the duplicate question so I'll leave my answer here:

Instance variables can be reached as helpers when defining columns for a resource. E.g.:

ActiveAdmin.register Company do
  controller do
    before_action :load_data, only: :index

    def load_data
      @loaded_data = expensive_operation
    end
  end

  index do
    column 'Something' do |company|
      loaded_data[company.id]
    end
  end
end

I found a reference to it on this answer on Github issues

julioolvr
  • 469
  • 4
  • 11
0

@Jiemurat 's answer to this question is the solution. This question is duplicative of How do I use instance variables, defined in the controller, in the view with ActiveAdmin?

Community
  • 1
  • 1
LikeMaBell
  • 1,529
  • 2
  • 13
  • 24