I understand that it is best practice to refactor as much of my code as possible into the models, however I am relatively new to rails, and programming as a whole. One of the concepts that seems to be causing me a little trouble is the nature of models, and understanding the scope or the availability of methods and variables.
First of all with a typical method written in the model what are the limitations (scope) that your method can be called on? How does the .self aspect work? What controllers / views have access to methods defined in the model?
I understand that these are rather basic principles but I believe that my “assumptions” with regard to this are causing me all manner of problems.
In Model-View-Controller (MVC):
Views have access to any public model methods. (Note: all ruby methods are public by default.) Of course, the model object must be instantiated first in the appropriate controller method, and must be instance variables (i.e.
@person) and not local variables (i.e.person) in the controller.Controllers also have access to any public model methods.
Protected methods limit access to within the class or within any of its children. Private methods limit access to within the class, only.
It appears to me that class methods, i.e.
def Person.some_method ..., are visible anywhere whether or not they are defined as public, protected, or private, although this is counter-intuitive.Regarding your question about self… You can use self for all calls to the model’s own methods from inside that model, and you won’t go wrong.
e.g. for Person model having first_name and last_name columns:
However, that’s overkill. You actually don’t need to use self for retrieving attributes in ActiveRecord, only for setting attributes, so the following is fine: