Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a '<<' method for an attribute on an ActiveRecord object

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?

like image 415
biagidp Avatar asked Jan 20 '26 20:01

biagidp


1 Answers

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.

like image 90
Andrew Avatar answered Jan 22 '26 10:01

Andrew