13
我有一个代理模型,它从底层数据库表中获取它的属性。但是对于一个特定的控制器操作,我希望在将代理记录传递给视图之前添加一些“临时”属性。将额外的运行时间attribs添加到activerecord对象
这可能吗?
我有一个代理模型,它从底层数据库表中获取它的属性。但是对于一个特定的控制器操作,我希望在将代理记录传递给视图之前添加一些“临时”属性。将额外的运行时间attribs添加到activerecord对象
这可能吗?
是的,您可以随时扩展您的模型。例如:
# 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
你将与其他属性。
感谢您的回复。我最终做到了,但我希望这会帮助其他人。很高兴知道人们仍在回应。 – nexar