Dylan Richards
Dylan Richards

Reputation: 786

How to search all nested resources without the parent resource?

My app's got Listings nested within Categories.

I can search all the listings when I'm in a particular category with this form:

<%= form_tag category_listings_path(@category), method: :get do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag 'Search', name: nil %>
  </p>
<% end %>

As you can see, I must make a get request to the category_listings_path and pass in the current Category.

However, this method fails when I want to put the search bar on a page where no Category exists!

How can I search for all Listings without needing to pass in a Category?

Upvotes: 0

Views: 71

Answers (1)

ptd
ptd

Reputation: 3053

Based on what you wrote, I'm guessing your routes look something like:

resources :categories do
  resources :listings
end

This means that all of your routes for listings require a category id. If you want a path for all listings, regardless of category, add:

resources :listings, only: [:index]

to your routes. Then you can have a form that searches to listings_path (which is the path that above route creates) and you don't need a category id.

Upvotes: 1

Related Questions