15

I have an Agent model which gets its attributes from the underlying database table. However for one particular controller action I would like to add some 'temporary' attributes to the Agent records before passing them on to the view.

Is this possible?

halfer
  • 19,824
  • 17
  • 99
  • 186
nexar
  • 11,126
  • 3
  • 29
  • 32

1 Answers1

23

Yes, you can extend your models on the fly. For example:

# GET /agents
# GET /agents.xml
def index
  @agents = Agent.all

  # Here we modify the particular models in the @agents array.

  @agents.each do |agent|
    agent.class_eval do
      attr_accessor :foo
      attr_accessor :bar
    end
  end

  # And then we can then use "foo" and "bar" as extra attributes

  @agents.each do |agent|
    agent.foo = 4
    agent.bar = Time.now
  end

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @agents}
  end
end

In the view code, you can refer to foo and bar as you would with other attributes.

Don Cruickshank
  • 5,641
  • 6
  • 48
  • 48
  • Thanks for your response. I did eventually work it out but I hope that this will help others. Good to know that people are still responding. – nexar Feb 10 '12 at 18:41