-->

Adding extra run-time attribs to an activerecord o

2020-02-27 11:46发布

问题:

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?

回答1:

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.