Reputation: 2497
I am looking to find the best way to setup the routes for my app.
The application allows users to register, post jobs and apply for jobs. The issue I am having is that two routes that should really show different things are linking through to the same pages.
My routes are as follows:
resources :users do
resources :apps
end
resources :jobs do
resources :apps
end
As a result of this I end up with two paths:
users/id/apps
jobs/id/apps
What I would like to do is use the first path to show job applications that a user has completed. I would then like to use the second path to show the owner of the job the applications they have received for that job.
The issue I am having is that both paths end up at apps#index
Any advice people can offer on how to best route this would be much appreciated! :)
Upvotes: 1
Views: 85
Reputation: 1831
Both those paths are potentially fine for what you want to do. When a request comes into
users/:user_id/apps
then you'll be able to do something like this in your controller to populate the list of apps:
@apps = User.find_by_id(params[:user_id]).apps
And in the case of the other path, you'll do the same but with params[:jobs_id]
, e.g.
@apps = Job.find_by_id(params[:job_id]).apps
In your controller you would have some conditional code that builds @apps depending on which path the request came in via (by looking to see if :user_id or :job_id is in params)... something like this:
if params[:user_id]
@apps = User.find_by_id(params[:user_id]).apps
elsif params[:job_id]
@apps = Job.find_by_id(params[:job_id]).apps
end
or maybe refactored to...
if params[:user_id]
@user = User.find(params[:user_id])
@apps = @user.apps
elsif params[:job_id]
@job = Job.find(params[:job_id])
@apps = @job.apps
end
Upvotes: 2
Reputation: 800
If you use the "resources" keyword, rails will just map to the default routes.
If you would like specific routes to map to something else, you should consider using "match."
For example:
match "users/id/apps" => "users/id/apps"
match "jobs/id/owners" => "jobs/id/owners"
This page shows a more detailed usage of it: http://guides.rubyonrails.org/routing.html
You also have the options to change the route to something else or the code itself.
Hope that helps.
Upvotes: 1