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

时间:2011-09-28 14:09:58

标签: ruby-on-rails-2

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

这可能吗?

1 个答案:

答案 0 :(得分:21)

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

# 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

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

相关问题