The model method is part of the ActionController::Dependencies module. This module juggles which classes are required and when.
class MyController < ActionController::Base
model :user
end
Rails can find and load the right classes as required (using some Ruby magic). This means that you can safely charge ahead and just use a model class without ever having to require it yourself:
class MyController < ActionController::Base
def display
@list = Foo.find(:all)
end
end
This is perfectly valid (even encouraged).
NOTE: The below is no longer important in Rails 0.13. The \SessionRestoreError has been removed from Rails. This means you can now safely store \ActiveRecord objects in the session.
If you are storing an \ActiveRecord object in session, any controller that will deal with that object must have the dependency already loaded. This normally means adding model :my_model in the ApplicationController. See HowtoAvoidSessionRestoreError for information on the matter.
Also, the SQL generated by SingleTableInheritance (STI) depends on what Rails knows to be the subclasses of the class you attempt to query. If the subclasses don’t happen to be loaded, the query doesn’t return all the results you’d expect.
The simple cure is to add dependencies in your ApplicationController. You can do this more than once, eg:
class ApplicationController < ActionController::Base
# Make sure that ActiveRecord is always aware of Entry's subclasses
model :entry, :catalog, :root_catalog
# Make sure that ActiveRecord is always aware of ElementDef's subclasses
model :element_def, :ref_component_def
end
category: Understanding
——
I have question. What if the model is within a module? For example:
model :‘blogpackage/article’
….
@article = BlogPackage::Article.search(params[:id], :include‘comment’)
How do Rails know when to load the ‘blogpackage/comment’ model? Do I put the model :‘blogpackage/comment’ in the controller or the Article.rb file?