简体   繁体   中英

Search form (Ransack gem)

I've been able to get a search form to work on my Bargain Stock Funds site ( http://www.bargainstockfunds.com ) by basing it on the example at http://railscasts.com/episodes/370-ransack . With a few modifications (Product->Fund, product->fund, products->funds), I'm able to get it to work.

The example app, by default, displays ALL records from the database table. For my particular app, this is NOT a viable option, because it covers over 10,000 stock funds, and loading them all up on the page takes FAR too much time.

How can I get the search form to display the entries ONLY if the number of entries is smaller than a given number? (I'm thinking of something like 200.) If the number of funds is too great, I want to provide a message saying something like "Too many funds - please narrow your search". If the number of funds is 0, I want to provide a message saying something like "No funds available - please broaden your search".

200 entries on a page is still quiet a lot, I am hoping that you will be using the will_paginate gem to control that, implementation is quite simple.

https://github.com/mislav/will_paginate/wiki

if you are using ransack then you can call a method like this.

def method
  if @search.result.count >= 200
    redirect_to root_path, notice: " Please narrow your search"
  elsif @search.result.count == 0
    redirect_to root_path, notice: "0 search results returned"
  else
   true
end

If you'd like to prevent too many from loading then you can always call a .limit(x) method on the @search.result

Hope that helps.

I was able to get my search form to work quickly by using the Kaminari gem to paginate the results. I tried will_paginate, but I couldn't get it to work for me. I suppose I could have stuck with the will_paginate gem, but Railscast covered Kaminari more recently than it covered will_paginate. Given how finicky Ruby on Rails can be and how outdated the details from older procedures can be, I decided to use Kaminari.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM