2011-09-28 8 views
13

Ho un modello di agente che ottiene i suoi attributi dalla tabella del database sottostante. Tuttavia, per una determinata azione del controller, vorrei aggiungere alcuni attributi "temporanei" ai record dell'agente prima di passarli alla vista.Aggiunta attribs in più run-time a un oggetto ActiveRecord

È possibile?

risposta

20

Sì, è possibile estendere i modelli al volo. Per esempio:

# 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 

Nel codice vista, è possibile fare riferimento a foo e bar come si farebbe con altri attributi.

+0

Grazie per la risposta. Alla fine l'ho risolto, ma spero che questo aiuti gli altri. Buono a sapersi che le persone stanno ancora rispondendo. – nexar

Problemi correlati