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