【发布时间】:2016-04-20 13:55:55
【问题描述】:
我测试过,它们实际上不起作用:
class User < ActiveRecord::Base
def self.call_protected_method
protected_method
end
def self.call_private_method
private_method
end
protected
def self.protected_method
puts "protected_method"
end
private
def self.private_method
puts "private_method"
end
end
我的意思是,它们不起作用,是您可以调用此示例中的所有方法。它们是否处于私有和/或受保护状态并不重要。
# in rails console:
User.call_protected_method # => protected_method
User.protected_method # => protected_method
User.call_private_method # => private_method
User.private_method # => private_method
这是为什么呢?忽略“私有”和“受保护”的原因是什么?
更新:我的问题不是如何做到这一点。我的问题是为什么这种方法在 Rails 模型中不起作用!?
【问题讨论】:
-
你预期会发生什么,结果发生了什么?
-
我的意思是,它们不起作用,是您可以调用此示例中的所有方法。它们是否处于私有和/或受保护状态并不重要。这是为什么?这是什么原因?