Home > Blockchain >  Rails how to search dropdown selection
Rails how to search dropdown selection

Time:04-22

Rails beginner here

I have a bunch of books in a database. I can access each of the books information by appending the book name to my url. (localhost/3000:books/booktitle1 ... localhost/3000:books/booktitle2 ... etc)

I have a dropdown menu that shows all the books in the database.

  <%=select_tag "book", options_from_collection_for_select(@books, "book_name", "book_name")%>

How do I make it so that when I make a selection on the drop-down menu, the webpage redirects to that book's information?

Meaning ... select "booktitle1" on dropdown menu, then my browser is sent to localhost/3000:books/booktitle1.

*Edit

It doesn't have to search on form selection exactly, selecting the book and then clicking a "Go" button is completely fine too. Just not sure how to implement it.

CodePudding user response:

After the form is submitted, you need to get the model object for the selected book. Then, get the url path for it. Finally, redirect to that path.

book = Book.find(params[:books])
path = url_for(book)
redirect_to path

The params[:books] returns the book's id, so I can query it using find. In your case, you're setting the value of your option attribute to the book's title. Consider changing that to id or use find_by to query the model instance. The tag I used is:

<%= select_tag 'books', options_from_collection_for_select(@books, 'id', 'title') %>

My form looks like this:

<%= form_with url: '/books', method: :post do |f| %>
  <%= select_tag 'books', options_from_collection_for_select(@books, 'id', 'title') %>
  <%= f.submit %>
<% end %>
  • Related