将额外的运行时属性添加到activerecord对象

nex*_*xar 15 ruby-on-rails-2

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

这可能吗?

Don*_*ank 22

是的,您可以动态扩展您的模型.例如:

# 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
Run Code Online (Sandbox Code Playgroud)

在视图代码中,您可以参考foobar使用其他属性.