mercredi 2 novembre 2016

Rails Search Form with dynamic queries

I basically have this problem except I also want the user to be able to add and remove search fields dynamically. Basically, the user selects the attribute field and the predicate from drop-down menus, then enters the text into a search box. So it looks like this:

student.last_name contains "stein"   

where "student.last_name" and "contains" were selected from drop-down menus.

But I'm adding a dynamic part to this, which brings up an option to join the previous query with a second (identical) query. The user is granted the option to join the query with either "or" or "and".

So basically, the user can makes searches like this:

student.last_name contains "ma" AND 
student.first_name does not equal "john" OR 
student.graduated equals "true"

It's the dynamic part that is tripping me up.

This my is my search.html.erb:

<%= form_tag(search_students_path, :method => "post", id: "search-form") do %>
  <div class="fields">
    <%= render :partial => 'students/condition_fields' %>
  </div>
  <%= submit_tag "Search", class: "search_button" %>
<% end %>

My _condition_fields.html.erb:

<%= select_tag "search_from", "<option> first_name </option>
                               <option> last_name </option>
                               <option> age </option>
                               <option> graduated </option>".html_safe %>

<%= select_tag "predicate",   "<option> equals </option>
                               <option> does not equal </option>
                               <option> contains </option>
                               <option> does not contain </option>".html_safe %>

<%= text_field_tag :search, params[:search], placeholder: "enter value...", class: "big_searchbox" %>

My controller code:

  def search
    @students = Student.search(params[:search], params[:search_from], params[:conjunction])

And finally, my model:

  def self.search(search, search_from, conjunction)
    if search
      query = [search_from + conjunction + "?", search]
      includes(:tags, :workstations).where(query)
    end
  end

My condition_fields is the part that I want to be dynamically adding and removing (along with a conjunction drop-down menu before each additional search condition).

I know some gems may help with this, but so far none of them easily provided the ability to add fields dynamically with "or" and "and" conjunctions, and I would like to learn this on my own for practice anyway.

Aucun commentaire:

Enregistrer un commentaire