Ruby/RoR:通过 super() 调用原始方法? [英] Ruby/RoR: calling original method via super()?
问题描述
在 RoR 应用程序中,我想在我的一个模型中专门使用 ActiveRecord 的 update_attributes() 方法,提取一些属性进行特殊处理,并将其余属性传递给原始的 update_attributes() 方法.详情:
In a RoR app, I want to specialize ActiveRecord's update_attributes() method in one of my models, extracting some of the attributes for special handling and passing the rest of them to the original update_attributes() method. The details:
class Premise < ActiveRecord::Base
...
def update_attributes(attrs)
attrs.each_pair do |key, val|
unless has_attribute?(key)
do_special_processing(key, val)
attrs.delete(key)
end
end
# use original update_attributes() to process non-special pairs
super.update_attributes(attrs)
end
...
end
对 super.update_attributes(attr) 的调用引发错误:
The call to super.update_attributes(attr) raises an error:
undefined method `update_attributes' for true:TrueClass
... 这让我怀疑我真的不理解 Ruby 中的 super 关键字.我错过了什么?具体怎么调用原来的update_attributes()方法?
... which makes me suspect I really don't understand the super keyword in Ruby. What am I missing? Specifically, how do I call the original update_attributes() method?
推荐答案
您想要:
super(attrs)
这将调用原始方法,将 attrs 作为参数传递给它.
That will call the original method, passing attrs as an argument to it.
就像现在一样,您正在尝试对原始 update_attributes 返回的true"值调用 update_attributes.
As it is now, you're trying to call update_attributes on the "true" value returned by the original update_attributes.
这篇关于Ruby/RoR:通过 super() 调用原始方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!