I've got an active record object that has custom accessors for storing arrays as comma separated text.
class Thing < ActiveRecord::Base
attr_accessible :object_list
def objects
self.object_list.split(",") rescue []
end
def objects=(input)
self.object_list = input.join(',')
end
end
I'd like to add the following
def objects<<(input)
unless self.object_list == nil
self.object_list << ",#{input}"
else
self.object_list = "#{input}"
end
end
So that I can do things like
thing.objects << 'this'
Is that possible?
I would do it this way:
class Thing < ActiveRecord::Base
def objects
@objects ||= read_attribute(:objects).split(',')
end
def objects=(input)
@objects=input
write_attribute(:objects, @objects.join(','))
end
end
That should allow you to treat objects like an array but have it save as a comma separated list in the db.
See Overwriting Default Accessors in the Rails API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With