Adding extra run-time attribs to an activerecord object

╄→гoц情女王★ 提交于 2019-12-08 23:39:33

问题


I have an Agent model which gets its attributes from the underlying database table. However for one particular controller action I would like to add some 'temporary' attributes to the Agent records before passing them on to the view.

Is this possible?


回答1:


Yes, you can extend your models on the fly. For example:

# 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

In the view code, you can refer to foo and bar as you would with other attributes.



来源:https://stackoverflow.com/questions/7584592/adding-extra-run-time-attribs-to-an-activerecord-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!