Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra run-time attribs to an activerecord object [duplicate]

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?

like image 503
nexar Avatar asked Sep 28 '11 14:09

nexar


People also ask

How do you duplicate a record in Rails?

You generally use #clone if you want to copy an object including its internal state. This is what Rails is using with its #dup method on ActiveRecord. It uses #dup to allow you to duplicate a record without its "internal" state (id and timestamps), and leaves #clone up to Ruby to implement.

What is an ActiveRecord relation object?

An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...


1 Answers

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.

like image 64
Don Cruickshank Avatar answered Jan 03 '23 01:01

Don Cruickshank