Jonathan Evans
Jonathan Evans

Reputation: 1034

Serializing ActiveRecord::Relation objects for storage

I am trying to build a reporting feature for my app and each report is essentially an active record relation / query with a name. I need to serialise these relations so that I can persist them and fetch them later. Is this possible?

Otherwise I have to resort to serialising the sql generated by the relations and then using that to query.

Upvotes: 1

Views: 897

Answers (1)

Ivan Shamatov
Ivan Shamatov

Reputation: 1416

I'm not sure it is really a good solution, but you can save your AREL as a string and then evaluate it like that:

For example, you want to save Bid.first

class Report < ActiveRecord::Base
  attr_accessible :arel

  def arel_eval
    args = @arel.split('.')
    model = args.shift.constantize
    args.inject(model) {|mod, met| mod.send(:#{met})}
  end
end

report = Report.new(arel: "Bid.first")    
report.arel_eval

Upvotes: 2

Related Questions