Controlling Information Access with the Rails Action Controller (Page 1 of 5 )
4.12 Restricting Access to Controller Methods
By default, all public methods in your controller can be accessed via a URL. You have a method in your controller that is used by other methods in that controller or by subclasses of that controller. For security reasons, you would like to prevent public requests from accessing that method.
Use Ruby’s private or protected methods to restrict public access to controller methods that should not be accessible from outside the class:
def add_accolade @employee = Employee.find(params[:id]) @employee.accolade += 1 double_bonus if @employee.accolade > 5 end
private def double_bonus @employee.bonus *= 2 end end
Ruby has three levels of class method access control. They are specified with the following methods: public, private, and protected. Public methods can be called by any other object or class. Protected methods can be invoked by other objects of the same class and its subclasses, but not objects of other classes. Private methods can be invoked only by an object on itself.
By default, all class methods are public unless otherwise specified. Rails defines actions as public methods of a controller class. So by default, all of a controller’s class methods are actions and available via publicly routed requests.
The solution shows a situation in which you might not want all class methods publicly accessible. The double_bonus method is defined after a call to the private method, making the method unavailable to other classes. Therefore, double_bonus is no longer an action and is available only to other methods in the Employee controller or its subclasses. As a result, a web application user can’t create a URL that directly invokes double_bonus.
Likewise, to make some of your class’s methods protected, call the protected method before defining them. private and protected (and, for that matter, public) remain in effect until the end of the class definition, or until you call one of the other access modifiers.