我在做 Agile Rails 书中的练习,在 application_controller.rb 中有一个私有(private)方法,定义为:
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create session[:cart_id] = cart.id cart
end
可以从 UserController#index(method) 内部调用此方法,但我不能这样调用它:
class UserController < ApplicationController
@cart = current_cart
...
这是为什么?
最佳答案
您在ApplicationController
中定义的方法是一个实例方法。因此,它可以从派生 Controller 的另一个实例方法中调用。这里:
class UserController < ApplicationController
@cart = current_cart
你正试图在类定义中调用它,而不是在类的实例方法中,所以它正在寻找一个不存在的类方法。
关于能够在派生 Controller 中调用私有(private)方法,请参阅示例 Protected and private methods in Rails .
编辑:来自 http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility :
In Ruby, “private” visibility is similar to what “protected” is in Java. Private methods in Ruby are accessible from children. You can’t have truly private methods in Ruby; you can’t completely hide a method.
关于ruby-on-rails - 为什么在 ApplicationController 上定义为私有(private)的方法可以在派生类的方法内部调用,但不能在派生类本身内部调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589046/