views:

66

answers:

1

How can I add a variable to a set of objects returned by ActiveRecord? I've looked around and none of the methods I've seen seem to work.

Thanks in advance!

+1  A: 

The question is vague and can be interpreted in a couple of ways.

  1. Adding a variable to a list.

    list_of_objects_returned_by_activeRecord << variable
    

    This seems too simple and is probably not what you're looking for.

  2. Adding a variable to each item in the list.

    Assuming your talking about instances of models, the simplest way is to add an attr_accessor to your model.

    class Model < ActiveRecord::Base
      ...
      attr_accessor :new_attribute
    end
    

    You probably want to set it to some value whenever the model is loaded so you want to add an after_initialize method to the model.For example, the following will add a nick_name attribute for every user loaded and default it to their first_name suffixed with "-O".

    class User < ActiveRecord::Base
      ...
      attr_accessor :nick_name
      def after_initialize
        self.nick_name = first_name + "-O"
      end
    end
    
    
    @user = User.first
    @user.first_name # => "Steve"
    @user.nick_name # => "Steve-O"
    @user.nick_name = "Tiny" # sets nick_name to "Tiny".
    @user.first_name # => Still "Steve"
    
EmFi