Where to put model search logic in a Rails application?
I'm trying to figure out the "best" place to put multi-attribute search form logic in a Rails application. The search form in question has several attributes which may or may not have values, and the data types differ between attributes. (For example, there are search options to search for items with a price attribute between two numbers, date ranges, string values, etc.) Also, the model in question has several nested attributes through has_a/has_many relationships and some of those attributes also need to be searchable.
The Rails mantra of thick model, thin controller makes me hesitant to try to aggregate the search logic into the controller. However, it also doesn't seem appropriate to put logic relating to constructing the search conditions in the model(s). Finally, in the spirit of DRY, I'm hesitant to hard-code a bunch of specific attribute names into some module since I will need to apply similar search logic to several unrelated models. Perhaps a naming convention of the form fields in the search view could be used to construct the right conditions? (Something like using prefixes like "min_", "max_", "startdate_" indicating the data type and search condition operator and the suffix being the name of the model and/or attribute?)
I've searched for advice on this, 开发者_高级运维but most of the advice seems inflexible (hardcoded attribute names, no support for nested attributes) or to use route-based searches which I don't think will work for my need (where 5-10 parameters may be used in a search at once).
Any suggestions on the "Rails way" of doing this?
If you are using 2.3.x, I've always found Searchlogic to be a solid and flexible starting point for searching ActiveRecord models where you don't need fulltext search. It supports associations, your own named scopes, etc.
If you are using Rails 3, the meta_search gem appears to offer similar functionality, but my experience with it is extremely limited.
精彩评论