views:

57

answers:

2

github url

I am using a simple search that displays search results:

@adds = Add.search(params[:search])

In addition to the search results I'm trying to utilize a method, nearbys(), which displays objects that are close in proximity to the search result. The following method displays objects which are close to 2, but it does not display object 2. How do I display object 2 in conjunction with the nearby objects?

@adds = Add.find(2).nearbys(10)

While the above code functions, when I use search, @adds = Add.search(params[:search]).nearbys(10) a no method error is returned, undefined methodnearbys' for Array:0x30c3278`

How can I search the model for an object AND use the nearbys() method AND display all results returned?

Model:

def self.search(search)
    if search
      find(:all, :conditions => ['address LIKE ?', "%#{search}%"])
      # where('address LIKE ?', "%#{search}")
    else
      find(:all)
    end
  end
+1  A: 

When you find(2), a model object is returned, but if you find(:all), and array is returned.

The nearbys method is only going to work on an instance of the model object. What if your search method returns an array of 10 addresses? You can't just invoke nearby on the array, you have to loop thru your array and apply nearby to each address yielded in the loop.

A: 

Without seeing your nearbys mehtod I can just about say that this is the perfect use-case for a scoped:

def self.search(term)
  if term
    scoped({ :conditions => ["address LIKE ?", term] })
  else
    scoped({})
  end
end

If nearby is defined on the class like I would think it would be used like this:

Model.search("pizza").nearby

And that is how you can scope.

Ryan Bigg