15

我有一个代理模型,它从底层数据库表中获取其属性。但是,对于一个特定的控制器操作,我想在将它们传递到视图之前向代理记录添加一些“临时”属性。

这可能吗?

4

1 回答 1

23

是的,您可以即时扩展您的模型。例如:

# 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

在视图代码中,您可以像使用其他属性一样引用foo和。bar

于 2012-02-09T16:22:39.170 回答