How I Implemented Filtering Feature for My Application Using Rails collection_select
As a part of my rails portfolio project assessment I had to complete a coding challenge— a drop-down filtering feature using ruby’s form helper collection_select to filter books by genre on my books index page in my app (the demo for the app: https://www.youtube.com/watch?v=AQfCcHATCjo&ab_channel=OlesyaMiller , Github: https://github.com/OlesyaMiller/book-store-rails-project).
Since I hadn’t created this functionality before I had to do some research to be able to implement it. I remembered that one of the lessons in the rails section had that functionality and that’s where I went first -https://learn.co/tracks/online-software-engineering-structured/rails/refactoring-with-helpers-and-model-methods/model-class-methods .
What I took away from the lesson was that I would have to pass the value returned from the collection_select input as a params key to #where method that I would call on the Book class in my Books controller to be able to filter the books list. In the lesson they use options_from_collection_for_select, not collection_select that I was looking for. So I googled “filtering with collection_select rails” and that again didn’t give me answers to what I was asked to do. That’s when I realized I had to actually understand how collection_select and filtering worked. After a bit of thinking I came to a conclusion that collection_select would just give me an input value which I would have to pass as a params key to my #where method. I found this source very helpful:
Let me break down the arguments of collection_select in my own words:
collection_select :model, :input name, Collection, value, label
Since my Book model has a genre_id foreign key, I decided make the value of the collection an :id (which would be an id of a Genre instance, clearly) , which would be saved in my params hash as params[:book][:search]
<%= form_tag(books_path, method: :get) do %> <%= collection_select :book, :search, Genre.all, :id, :name, include_blank: true %> <%= submit_tag ("Search") %><% end %>
And finally the query in my Books controller:
@books = Book.where(genre_id: params[:book][:search])