Bondhan Sarker
Bondhan Sarker

Reputation: 128

rails route: same url pattern with different parameter

Routes:

get 'home/index' => "home#index" 
namespace :lawyers do                                                                                   
   get 'all/:division/:district' => "profiles#index", as: :division_district_all
   get 'all/:speciality/:sub_speciality' => "profiles#index", as: :speciality_subspeciality_all
 end

Home controller #Index view:

<% @districts.each do |district| %>
      <%= link_to district.name, lawyers_division_district_all_path(district.division.name.parameterize,district.slug) %>
<% end %>

<% @sub_specialities.each do |sub_speciality| %>
      <%= link_to sub_speciality.name,lawyers_speciality_subspeciality_all_path(sub_speciality.speciality.name.parameterize,sub_speciality.name.parameterize)%>
 <% end %>

Profile Controller #index:

raise params.inspect

Every time I hit with speciality and sub_speciality but this shows division and district value in params. It conflicts because the pattern is similar. How can I get rid of this ?

Upvotes: 0

Views: 1470

Answers (1)

Jorge Caballero
Jorge Caballero

Reputation: 749

You are going to need to separate the destination method on the controller and update the routes.

I would recommend this approach:

namespace :lawyers do                                                                                   
   get 'division/:division/:district' => "profiles#division", as: :division_district_all
   get 'speciality/:speciality/:sub_speciality' => "profiles#speciality", as: :speciality_subspeciality_all
 end

Update: Based on strong requirements, you could use query params all/:division/:district?query_by=divison you would only need one route.

get 'all/:primary/:secondary' => "profiles#index", as: :lawyers_all

And then in the controller, manage the logic with something like

def index
  case params[:query_by]
  when 'division'
    # Division logic here
  when 'speciality'
    # speciality logic here
  else
    # Error handling here
  end
end

Update 2: As you mentioned on the comments, URL cannot change. Still you would need only one route

get 'all/:primary/:secondary' => "profiles#index", as: :lawyers_all

And check existence on db based on the params, this will impact the performance of your app by creating a lot of db requests and also will create the potential issue of matching with the incorrect classes.

def index
  if Division.find_by(name: params[:primary]).present?
    # Division logic here
  elsif Speciality.find_by(name: params[:primary].present?
    # speciality logic here
  else
    # Error handling here
  end
end

Upvotes: 1

Related Questions