So in my app a Client has many sites, my routes and controller are nested under clients and they all appear on the show page (code below).
What I am trying to acheive is implimenting a Ransack search form and sort links on the clients show page so a user can search the associated sites ect.
Currently when I create the site that is associated to the client it displays ALL Sites across all clients no matter what client a site is associated to.
my routes:
resources :clients, controller: 'clients' do
resources :sites, controller: 'clients/sites', except: [:index]
end
client controller /show action
class ClientsController < ApplicationController
def show
@client = Client.find(params[:id])
@q = Site.ransack(params[:q])
@sites = @q.result(distinct: true).page(params[:page]).per(5)
end
end
My models:
class Client < ApplicationRecord
has_many :sites, dependent: :destroy
end
class Site < ApplicationRecord
belongs_to :client
end
My search form and sort links on the Clients/show[:id] page
<%= search_form_for @q do |f| %>
<%= f.search_field :site_ident_or_site_name_cont, :class => 'form-control', :placeholder => 'search client...' %>
<% end %>
<%= sort_link(@q, :site_name, 'Site Name') %>
what I want to do is to only search the sites associated to the client being displayed. Any assistance here would be greatly appreciated.
So the solution was a 2 part solution thanks to Taryn East's answer above for getting the ball rolling for me!
the controller action dose need to be scoped like she had suggested like so:
def show
@client = Client.find(params[:id])
# scope by just the sites belonging to this client
@q = @client.sites.ransack(params[:q])
@sites = @q.result(distinct: true).page(params[:page]).per(5)
end
then a few modifications to the search form:
<%= search_form_for @q, url: client_path(params[:id]) do |f| %>
<%= f.search_field :site_name_cont, :class => 'form-control', :placeholder => 'search client...' %>
<% end %>
This fixed the problem