Forum: Ruby on Rails little Live search problem

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Rob B. (Guest)
on 2006-06-07 19:23
Works fine but when you use backspace or delete on the search word and
it hits 0 characters it displays ALL the Test names in the database!

def live_search
    @phrase = request.raw_post || request.query_string
    a1 = "%"
    a2 = "%"
    @searchphrase = a1 + @phrase + a2
    @results = Test.find(:all, :conditions => [ "test_name LIKE ?",
@searchphrase])

    @number_match = @results

    render(:layout => false)
end
Alex W. (Guest)
on 2006-06-07 20:47
Rob B. wrote:
> Works fine but when you use backspace or delete on the search word and
> it hits 0 characters it displays ALL the Test names in the database!
>
> def live_search
>     @phrase = request.raw_post || request.query_string
>     a1 = "%"
>     a2 = "%"
>     @searchphrase = a1 + @phrase + a2
>     @results = Test.find(:all, :conditions => [ "test_name LIKE ?",
> @searchphrase])
>
>     @number_match = @results
>
>     render(:layout => false)
> end

@results = @phrase.empty? ? nil : Test.find(:all, :conditions =>
["test_name LIKE ?", @searchphrase])
Rob B. (Guest)
on 2006-06-07 21:07
Alex W. wrote:
> @results = @phrase.empty? ? nil : Test.find(:all, :conditions =>
> ["test_name LIKE ?", @searchphrase])

Thanks Alex but I have .empty? in my view for the results.
Any way around this?

NoMethodError in Search#live_search

Showing app/views/search/live_search.rhtml where line #1 raised:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.empty?

Extracted source (around line #1):

1: <% if @results.empty? %>
2:   No match for '<%=h @phrase %>.'
3: <% else %>
4:   <% @results.each do |result| %>
Justin M. (Guest)
on 2006-06-07 21:23
(Received via mailing list)
Try @phrase.blank? instead, as it will check for a nil value before
attempting to call empty?.

J
Rob B. (Guest)
on 2006-06-08 02:16
Justin Mecham wrote:
> Try @phrase.blank? instead, as it will check for a nil value before
> attempting to call empty?.
>
> J

Didn't work, same result as above.
Rob B. (Guest)
on 2006-06-08 02:19
Hang on just swapped the view to say .blank? too and it works. Thanks J
and Alex.
This topic is locked and can not be replied to.