UPDATE:
How do I add a virtual attribute to a model and preserve the active record relation.
I tried the below, but .each returns an array, not active record. What other method can I use?
My set_listable_for
method is converting an activerecord relation into an array. I want to preserve the ActiveRecord Relation.
At runtime, I added an attr_access to an active record model.
def add_listable_attribute_to(*relation)
relation.each do |rel|
rel[1].first.class.class_eval do
attr_accessor :listable
end
end
end
Then I used this method to set the value of the attribute to the same value for all records....
def set_listable_for(relation, object)
relation.each do |record|
record.listable = object
end
end
However, my ActiveRecord relation gets converted to an Array afterwords.
How to I preserve the Active Record relation, as I don't want an array. Since I continue to use it here and continue to scope and query on it...
def union_scope(*relation)
add_listable_attribute_to(*relation)
listable = relation.first[0]
combined = set_listable_for(relation.first[1], listable)
relation.drop(1).each do |relation_set|
listable = relation[0]
set_listable_for(relation_set[1], listable)
combined = combined.or(relation_set[1])
end
combined
end
Thank you
ActiveRecord::Relation
should behave. It represents a scope or query that can be run against the database (no records included yet). And as soon as you need one or more of the actual records, it loads the records and returns them in an array. This happens if you call a method likefirst
,count
, oreach
on the Relation. Therefore your question is unclear to me because you request to disable its core functionality. – spickermann