I got a little problem to understand where should I add an method that all the models can have access to it. I read other similar posts but it’s not very clear where to add it. Some of them said about add it on “/lib” as a module an then include it in the model class (Already try this without luck). So what it’s the best practice for add this?
I’m trying the following:
My module on: /lib/search.rb
module Search
def self.search(params,columns_search)
srch = params[:search]
if srch.blank?
scoped
else
search= []
#Add conditions for the search
columns_search.map do |column|
search << (sanitize_sql_for_conditions ["LOWER(CAST(#{column} as TEXT)) LIKE ?", "%#{srch.downcase}%"])
end
where("(#{conditions.join(" and ")})")
end
end
On my model cars.rb
class Cars < ActiveRecord::Base
include Search
attr_accessible :name
end
But i’m getting the following error on my console:
Started GET “/cars” for 127.0.0.1 at 2012-08-01 11:56:54 -0500
ActionController::RoutingError (uninitialized constant Car::Search):
app/models/car.rb:2:in `’
Any help will be appreciated! 🙂
The technique you mention seems like a reasonable approach – create a module (which will probably live in
/lib) that defines the methods you want the models to have, and then include it in each model that needs it.For instance, my current project has Images, Videos and Audios, all of which have certain method that should be available to them because they’re all types of media.
I define a module in
lib/media.rb:And then in each of the media models, I include it:
I can then call
Video.first.do_something, just as though the method were defined in the model.