I have a common method that exists in my model because it is called by my model. Retrospectively, my view also requires this model method. In order to accomplish this, I have:
- moved the model method to the
application_helper.rbfile - my model calls the application_helper method by adding
include ApplicationHelperat the top of my ActiveRecord model
Functionality wise, it works. But is this good practice?
My Model looks like this:
class Client < ActiveRecord::Base
include ApplicationHelper
end
Writing
include ApplicationHelperin to your model is bad practice because ApplicationHelper is a nice place to put tons of helper functions you need in your views. These functions will end up being imported as instance methods of your model. These functions are mostly unrelated to your model and will not work if they depend on things likeparamsorrequest. Here are two other options:Option 1:
You can just define the method inside the
Clientclass, and then call it from the view, like this:And then in your view:
Option 2:
Make a separate module in
liband include it in the places you need it. The file name should match the module name for auto-loading to work.In
lib/my_module.rb:In your model:
Include the module in ApplicationHelper so it is available to all your views:
Then in your view you can call it easily: