ruby-on-rails-2 – 向activerecord对象添加额外的运行时间

我有一个代理模型,它从基础数据库表中获取它的属性.然而,对于一个特定的控制器动作,我想在将代理记录传递给视图之前向代理记录添加一些“临时”属性.

这是可能的吗?

所有的帮助感激不尽.

Purvez

解决方法

是的,你可以在飞行中扩展你的模型.例如:
# 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.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...