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?
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.
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).
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With