How To Handle Model In Module?
The number of models in your Ruby on Rails application is growing and one day you will get a brilliant idea.. Let’s put them to modules (that is to different subdirectories in the modules directory). Well, I had this day some weeks ago and, honestly, it is not a good idea… Helpers and tools in RoR, that work without any problems and manual changes when models do not use modules, will require some manual changes to work.
Here is a list of my experiences…
Paginate Helper
A model name for the paginate helper cannot be :model anymore, you have to write 'module/model'.
For a model without a module:
-
@book_pages, @books = paginate :book, :per_page => 10
For a model in a module:
-
@book_pages, @books = paginate ‘library/book’, :per_page => 10
View
Any reference to a model has to contain also a module name: Model.content_columns has to be written as Module::Model.content_columns.
For a model without a module:
-
<% for column in Book.content_columns %>
-
<td><%=h book.send(column.name) %></td>
-
<% end %>
For a model in a module:
-
<% for column in Library::Book.content_columns %>
-
<td><%=h book.send(column.name) %></td>
-
<% end %>
Scaffold
Files generated for a model in a module with the scaffold script do not work. It is necessary to fix the two above mentioned problems, that is to fix:
- the paginate problem in a controller
- the view problem in the list.rhtml file
I also tried the AJAXScaffold, but it relies that the model name does not contain also a module name. I tried to fix it, but I did not have a lucky day.
Generate
To create a model in a module with the generate script use the module/model notation, e.g.:
For a model without a module:
-
ruby script/generate model book
For a model in a module:
-
ruby script/generate model library/book
Model Relationship
If there is a relationship between models in two different modules, it is necessary to specify the :class_name option, otherwise the model in a different module will not be recognised.
For models not in a module:
-
class Review < ActiveRecord::Base
-
belongs_to :book
-
end
For models in different modules:
-
class Review < ActiveRecord::Base
-
belongs_to :book,
-
:class_name => "Library::Book"
-
end
That is all. To have a model in a module is solvable, but definitely not easy to use.
If you have a lot of models and you decided to store them in different modules, my comments may help you.










