提问人:Davi Luis 提问时间:12/14/2022 更新时间:12/14/2022 访问量:36
在 Rails 中覆盖继承的控制器方法的一部分
Override part of the inherited controller method in Rails
问:
我在第一堂课上有一个方法
class1
def method(param_test)
if !organization.empty?
organization = test(param_test)
end
end
end
类 2 继承自类 1
class2 < class1
end
我想修改该行organization = test(param_test)
而不必在 class2 中复制整个方法
有可能?
答:
0赞
spickermann
12/14/2022
#1
我会将逻辑分为两种方法,如下所示:
# in the parent class
def method(param_test)
if !organization.empty?
organization = fallback(param_test)
end
end
def fallback(param)
test(param)
end
然后重写子类中的一个方法,如下所示:
# in the child class
def fallback(param)
# logic to return the expected response
end
另一种方法是更改子类中的方法。但这可能是什么样子取决于具体的用例和方法的内部结构。test
test
评论