简体   繁体   中英

Ruby on Rails: How to implement search function

I'm very new to Ruby on Rails and actually, I'm trying to implement a search function into my Ruby on Rails page. It's a page where you can add users to a database, you can also edit or delete them. There is my index page where all of those users are getting listed, and, above this table, there is a search function (well, it's just a text field and a button).

What I want to do it now: I want to implement a search function which is searching for the surname, room, key, manager and so on. I already tried some things but I finally don't know how to implement a search function in general (what should I write, where should I write it? I heard from models and controllers, but anyway I'm not 100% sure). I would be really pleased if you could help me through this!

Cheers, absolado

Here below is the sample code of simple search.

index.html.erb

<% form_tag projects_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

here your_model.rb

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

here your_controller.rb

def index
  @projects = Project.search(params[:search])
end

You can use a gem for this in case you do not want to implement it yourself. Ransack is a very popular gem which can support all this functionality along with helpers for your views, advanced search matchers and many more. I suggest you have a look on this before proceeding with your own implementation.

This looks like a job for Datatables . I have used this many times in my apps. Aside from searching an attribute in your records, it also has sortable column feature.

It is important to outline that Datatable is a javascript package which builds a robust table with filter, order, pagination goodies but by default it is not done server-side.

Which means that if you have a large dataset then you might be in trouble as all your records will be pumped to the client's browser as a huge json and Datatable will parse and fill in the table for you.

Datatable provides support to server-side pagination, filter and so on, but then you will have to implement those features into your back-end.

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