Reputation: 3193
I'm creating an entry form that I want to only be accessible when three url params are in place: example.com/entries/new/2011/01/27
If someone tries to access any other url (i.e. example.com/entries/new
or example.com/entries/new/2011/
) I want Rails to set an :alert and bounce the user back to the index page.
Currently, I only have this code in my routes.rb match '/entries/new/:year/:month/:day' => 'entries#new'
. What do I need to do to control the redirection if the proper params aren't in the URL? Would I check for each param in the controller and then perform a redirect_to
, or is this something I can do from the routes.rb file exclusively? If it's the former, is there an easier way to check that all three params exist other than:
if params[:year].nil && params[:month].nil && params[:day].nil redirect_to ...
Upvotes: 0
Views: 997
Reputation: 47578
This route requires the presence of all three parameters:
match '/entries/new/:year/:month/:day' => 'entries#new'
With only that route, GET /entries/new
will result in:
No route matches "/entries/new"
You can redirect from within routes.rb
like this:
match '/entries' => 'entries#index'
match '/entries/new/:year/:month/:day' => 'entries#new'
match "/entries/new/(*other)" => redirect('/entries')
The second line matches paths where all three parameters are present. The third line matches all other cases of /entries/new
using "route globbing", and does the redirect. Requests matched by the third line will not hit EntriesController#new
.
Note: you may not need the first line if you've already defined a route to EntriesController#index
-- but watch out for resources :entries
, which will redefine index
and new
.
More info can be found in the guide Rails Routing From the Outside In. When using date parameters, constraints are a good idea (Section 4.2)
Upvotes: 1