Adding extra run-time attribs to an activerecord o

2020-02-27 10:58发布

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条回答
戒情不戒烟
2楼-- · 2020-02-27 11:30

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.

查看更多
登录 后发表回答