【问题标题】:Adding extra run-time attribs to an activerecord object [duplicate]向 activerecord 对象添加额外的运行时属性 [重复]
【发布时间】:2011-09-28 14:09:58
【问题描述】:

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

这可能吗?

【问题讨论】:

    标签: ruby-on-rails-2


    【解决方案1】:

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

    # 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

    【讨论】:

    • 感谢您的回复。我最终确实解决了这个问题,但我希望这对其他人有帮助。很高兴知道人们仍在回复。
    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    相关资源
    最近更新 更多