加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:10:00 所属栏目:百科 来源:网络整理
导读:我有一个代理模型,它从基础数据库表中获取它的属性.然而,对于一个特定的控制器动作,我想在将代理记录传递给视图之前向代理记录添加一些“临时”属性. 这是可能的吗? 所有的帮助感激不尽. Purvez 解决方法 是的,你可以在飞行中扩展你的模型.例如: # GET /ag
我有一个代理模型,它从基础数据库表中获取它的属性.然而,对于一个特定的控制器动作,我想在将代理记录传递给视图之前向代理记录添加一些“临时”属性.

这是可能的吗?

所有的帮助感激不尽.

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读