Praveen George
Praveen George

Reputation: 9725

Drop Down List With Search Button In Rails

I have a customer model with the following collection:

@doctors =  Customer.joins(:user).where(users: {role: User.roles[:doctor]}) 

which joins the user table and customer tables where user role is "doctor".

In my Customers index view currently I am listing all the customers, now I want to add a search filter using a Drop down list with a search button, where the list contains the first name of the Doctors. If I press the search button it should show only customers created by that particular doctor selected from the drop down list.

1. How to add a drop down list with search button which displays only first names of doctors ?


2. How to filter my customers listing when I select a particular doctor from the drop down and click on search button ?


<div class="btn-group">
            <button type="button" class="btn btn-success btn-sm"><b>Search By Dr.</b></button>
            <button type="button" class="btn btn-success btn-sm" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            	<span class="caret"></span>
            	<span class="sr-only">Toggle Dropdown</span>
            </button>
            <ul class="dropdown-menu">

              <li><a href="#">List All Customers</a></li>
            <% @practices.each do |practice| %>
              <li><a href="#">Dr.<%= practice.firstname %></a></li>
            <% end %>
            </ul>
        </div>

The above is the code that I am currently using, but is it correct way of Rails ?

Upvotes: 1

Views: 8667

Answers (3)

LukeS
LukeS

Reputation: 481

  1. You can simply use the following tag in your rails view:

    <%= select("doctor", "firstname", @doctors.all.collect(&:firstname)) %>

  2. Then in your controller you'd have something like this:

    def index if params[:doctor] @customers = Customer.joins(:user).where(users: {role: User.roles[:doctor]}, firstname: params[:doctor][:firstname].downcase) else @customers = Customer.all end end

Upvotes: 1

Prakash Laxkar
Prakash Laxkar

Reputation: 854

You can do this auto_complete rails. Have a look on http://railscasts.com/episodes/102-auto-complete-association

Thanks

Upvotes: 1

Asad Ali
Asad Ali

Reputation: 660

Answer 1:

you can do this task using JS I will recommend you to use one of these jquery plugins for search bars Select2 and Chosen.

My personal experience with select2 is impressive.

it loads data via ajax and cache as well to avoid repeat calls. Its GUI give u a Google like feel. read its documentation and use it.

Answer 2:

select2 also give u events like change so u can make another ajax call to load filterd customers.

Upvotes: 2

Related Questions