I'm working on implementing a search form in a ruby on rails appli开发者_运维百科cation. The general idea is to use form_tag to submit the search fields (via params) to a search function in the model of the class I'm trying to search. The search function will then iterate through each of the params and execute a scoping function if the name of the function appears in params.
The issue is that when I call the search on a collection like so:
@calendar.reservations.search({:search_email => "test"})
I don't know how to refer to the collection of @calendar.reservations from within the search function.
Additionally I'm confused as to why @calendar.reservations.search(...) works, but Reservations.all.search gives me an error saying you can't call an instance method on an array.
I've got the details of the search method over here: https://gist.github.com/783964
Any help would be greatly appreciated!
I don't know how to refer to the collection of @calendar.reservations from within the search function.
If you use self
(or Reservation
, it's the same object) inside the classmethod, you will access the records with the current scope, so in your case you will see only the reservations of a particular calendar.
[edit] I looked at you search function, and I think what you want is:
def self.search(search_fields)
search_fields.inject(self) do |scope, (key, value)|
scope.send(key, value)
end
end
Additionally I'm confused as to why @calendar.reservations.search(...) works, but Reservations.all.search gives me an error saying you can't call an instance method on an array.
@calendar.reservations
does not return a standard array but a (lazy) AssociationCollection, where you can still apply scopes (and classmethods as your filter
). On the other hand Reservation.all
returns a plain array, so you cannot execute search
there (or any scope, for that matter).
You don't really need a search
method at all, as far as I can tell.
Simply use where
:
@calendar.reservations.where(:search_email => 'test')
I would strongly encourage you to look at the MetaSearch GEM by Ernie Miller. It handles the kind of thing you're working on very elegantly and is quite easy to implement. I suspect that your view code would almost accomplish what the GEM needs already, and this would take care of all your model searching needs very nicely.
Take a look and see if it will solve your problem. Good luck!
Reservation.all.search
doesn't work because it returns all the results as an array, while Reservation.where(..)
returns an ActiveRecord object (AREL). Reservation.all actually fetches the results instead of just building the query further, which methods like where
, limit
etc do.
精彩评论