I’ve been struggling for few days on this one:
I have a search form in my navbar that runs a search in the :address column of my Users table through the job model. Here is the index method of my JobsController:
def index
@jobs = if params[:address]
Job.joins(:user).where(users: { address: params[:address].downcase
}).paginate(page: params[:page], per_page: 3)
else
@jobs = Job.paginate(page: params[:page], per_page: 3).order(‘id DESC’)
end
end
Here is the form:
<%= simple_form_for(jobs_path, method: :get) do %> <%= text_field_tag :address, params[:address], placeholder: " Votre Ville..." %> <%= submit_tag 'Rechercher', class:'btn btn-default' %> <% end %>
Here is my route file:
Rails.application.routes.draw do
devise_for :usersget ‘static_pages/home’
get ‘static_pages/faq’
get ‘static_pages/about’
get ‘static_pages/cgu’
root ‘static_pages#home’
get ‘/faq’, to: ‘static_pages#faq’
get ‘/about’, to: ‘static_pages#about’
get ‘/contact’, to: ‘static_pages#contact’
get ‘/cgu’, to: ‘static_pages#cgu’
get ‘/signup’, to: ‘users#new’
get ‘/login’, to: ‘sessions#new’
post ‘/login’, to: ‘sessions#create’
delete ‘/logout’, to: ‘sessions#destroy’resources :jobs, only: [:show, :index]
resources :users do
resources :jobs
end
The Jobs route is there twice as I need to make the index and view actions available for non logged in users / visitors.
Rails routes shows:
My problem is, that the request gets lost in routes and sometimes goes to the wrong controller. If I’m on the Jobs#index page : http://localhost:3000/jobs and run a search for a city like “Nantes”. The query runs fine:
Started GET “/jobs?utf8=%E2%9C%93&address=Nantes&commit=Rechercher” for
127.0.0.1 at 2017-11-20 08:34:48 +0400
Processing by JobsController#index as HTML
Parameters: {“utf8”=>“✓”, “address”=>“Nantes”, “commit”=>“Rechercher”}
Rendering jobs/index.html.erb within layouts/application
(0.4ms) SELECT COUNT(*) FROM “jobs” INNER JOIN “users” ON “users”.“id” =
“jobs”.“user_id” WHERE “users”.“address” = $1 [[“address”, “nantes”]] … … …
If I’m running the query from my root page ie: StaticPagesController, the query is sent to StaticPagesController and NOT to JobsController:
Started GET “/?utf8=%E2%9C%93&address=Nantes&commit=Rechercher” for 127.0.0.1
at 2017-11-20 08:37:49 +0400
Processing by StaticPagesController#home as HTML
Parameters: {“utf8”=>“✓”, “address”=>“Nantes”, “commit”=>“Rechercher”}
Rendering static_pages/home.html.erb within layouts/application
How do I make sure the query is always sent to the correct controller, regardless of where I am? Nothing that I’ve tried in the form seems to work! Thank you guys.