开发者

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

This question already has answers here: Non persistent ActiveRecord model attributes 开发者_如何学C (5 answers) Closed 1 year ago.

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜