Rails Routing based on Parameters - ruby-on-rails-3

I am working on a Rails app, and I am looking for a way to route to different actions in the controller based on the existence of parameters in the url.
For example I want website.com/model to route to model#index, however I want website.com/model?opt=dev to route to model#show. Is there some way this can be done?

Use route constraints to look at the request object and see if it has URL parameters. If you're using restful routes, you want to put this "one-off" before the restful route. Something like this:
get 'users' => 'users#show', constraints: { query_string: /.+/ }
resources :users
So what this is saying is that if you request "/users?opt=dev" then it will match your special case. Otherwise, it falls through to your normal restful route to the index action. Your model#show action will then have to know to pick up the param[:opt] and do whatever with it.
Also, note that the regex is very loose and it's simply checking for ANY param...you'll want to tighten that up to fit whatever you're trying to do.

Not strictly the same, but if you came to this post and were wondering how to do the same via a POST, then you can do it based on the request_paramters.
for your routes.rb ..
module MyConstraintName
extend self
def matches?(request)
request.request_parameters["routeFlag"] == "routeToModelShow"
end
end
match "pages/:id", :via=>:post, :controller=>"model", :action=>"show", :constraints => MyConstraintName
and in your form for example..
<%= hidden_field_tag :routeFlag, "routeToModelShow" %>

Related

How do I create routes for a controller that does nothing with models in Rails?

Still pretty new to Rails, so if I'm taking the completely wrong approach, please feel free to straiten me out.
How do I make routes.rb aware that there's a root controller full of actions that don't manipulate models, while preserving the route helper methods? I'd like it to respond to requests like these:
http://localhost/download
http://localhost/share
With route helpers like
download_app_path
share_path
but without static named routes like these:
match '/download' => 'site#download', :as => :download_app
match '/share' => 'site#share', :as => :share
from a SiteController that doesn't create, show, or otherwise manipulates models from my app.
I've tried using an approach like this, but it works without generating the route helpers ( naturally )
match '/:action', :controller => 'site'
I could theoretically do without the route helpers, but I think they're a bit easier to read than passing hashes of url options to link_to or form methods.
Is there a way to accomplish a more resourceful root controller, or is what I'm trying to do unconventional for Rails?
Edit
For clarity, here's what this SiteController class looks like:
class SiteController < ApplicationController
def download
#custom_options = { .. }
end
def share
#custom_options = { .. }
end
def about
end
end
Its purpose is to allow me to collect pages that don't interact with resources ( such as Users or Friendships ) into a single controller and maintain them all in one place. I'm trying to set this controller up as the application root controller - so all paths from this controller will be directly off the app host ( myapp.com/download )
Thanks in advance!
routes and resources are not tied to models. it's just a RESTful convention. if you just want to use the index actions, in your example download and share could be done like
resouce :download, only: [:index]
resouce :share, only: [:index]
see all the examples in the guides http://guides.rubyonrails.org/routing.html
if you want to add the download and share functionality to some "resource" like, say a picture, then you would do something like:
resources :pictures do
get 'download', :on => :member
get 'share', :on => :member
end
a resource always has and endpoint /pictures for example. so if you want to have paths directly to your host, then you need to provide custom matchers in your routes like you did in your examples.

Questions about rails3 routes

I'm upgrading my app to rails 3, and I am a bit confused about some of the routes. The resourceful ones are easy enough, but how can I set a generic rule for all actions in a specific controller. I tried something like this:
get 'custom/:action/' => {:controller => :custom}
But that didn't work. It seems the new format is "controller#action", but how can I specify the action to be variable?
Also, other than using named routes or resources, is it possible to do shorthand notation to name routes in a specific controller?
i.e. rather than:
get '/tasks', :controller => :home, :action => :tasks, :as => 'tasks_home'
get '/accounts', :controller => :home, :action => :accounts, :as => 'accounts_home'
is it possible to do something a little cleaner, like:
controller => :home do
get :tasks
get :accounts
end
And that would automatically created the named routes?
You can use action as a variable like this:
resource :custom do
match ':action'
end
This will generate
/custom/:action(.:format) customs#:action
custom POST /custom(.:format) customs#create
new_custom GET /custom/new(.:format) customs#new
edit_custom GET /custom/edit(.:format) customs#edit
GET /custom(.:format) customs#show
PUT /custom(.:format) customs#update
DELETE /custom(.:format) customs#destroy
So it will handle your action as a variable URL-s and will add some default CRUD actions as well.
Note that the controller name here is in plural. If you would like to use a route for a controller which name is in singular, use resources instead of resource.
The answer to the second question is almost identical to the first one, use resource:
resource :home do
get :tasks
get :accounts
end
generates:
tasks_home GET /home/tasks(.:format) homes#tasks
accounts_home GET /home/accounts(.:format) homes#accounts
home POST /home(.:format) homes#create
new_home GET /home/new(.:format) homes#new
edit_home GET /home/edit(.:format) homes#edit
GET /home(.:format) homes#show
PUT /home(.:format) homes#update
DELETE /home(.:format) homes#destroy
Note that the matched controller names are in plural again, because of the convention.
Looks like this is related to the persisted field being set to false on nested ActiveResource objects: https://github.com/rails/rails/pull/3107

Rails -- rename restful route

I wanted to know what the easiest way to rename a restful route is. Basically I have a controller called Employees and rather than have employees/new I want employees/hire to be used and achieve the same thing and make employees/new an invalid url.
For your specific need, the guide has exactly this example for new, edit, this should work:
resources :employees, :path_names => { :new => 'hire' }
http://guides.rubyonrails.org/routing.html#overriding-the-new-and-edit-segments
One of the best sources of data on routes is the rails guide:
Rails Guide on Routes, also the command
rake routes
This command will show you all the current routes.
But in answer to this specification question
if you look into your routes file you can create new routes
manually.
match 'employee/hire' => 'Employees#new', :via => :get, :as => 'employee_path'
the first argument matches what the browser is looking for.
The second argument is the controller and method.
The third is if it is a get, put, post, or delete call.
The fourth is the name for the path so you can access with the standard name_path type of call from code.
This makes sense?

Rail3 routes [edit problem]

Example I have had configured my routes as
match '/cellphones/:permalink/:charger', :controller => 'mycontroller', :action => 'myaction'
resources :cellphones
Everything ok when I put something like this localhost/cellphones/nokia3323/lion but I can't edit a cellphone because have the same structure localhost/cellphones/edit/4
Routes that are defined earlier take precedence, so you could make the edit route accessible again by reversing the order that you've declared your routes in. Since a route of /cellphones/edit/:id is more restrictive than /cellphones/:permalink/:charger, the edit route will match if the second part of the route is "edit" and pass through to your other route if it's something else.
However, you most likely don't actually have a /cellphones/edit/:id route, because what's created by resources :cellphones is /cellphones/:id/edit which is much harder to distinguish from /cellphones/:permalink/:charger since both have the wildcard part of the route as the second segment.
The easiest way the fix the problem would be to change the /cellphones/:permalink/:charger route so it's easier to distinguish. You could use something like /cellphones/p/:permalink/:charger ("p" for permalink), or anything else that's easy to distinguish from the RESTful routes created by resources.
There's a few other ways you could approach it as well, such as using segment contraints or adding more restful actions.
I found the solution, just had to change the order
resources :cellphones
match '/cellphones/:permalink/:charger', :controller => 'mycontroller', :action => 'myaction'

URL helper for a post route in a resource

I have a resourceful route, with a post route nested within it:
resources :groups, :only => [:index, :show] do
post 'send_audit_reminder', :on => :member
end
If I run rake routes, this route shows up just fine:
send_audit_reminder_group POST /groups/:id/send_audit_reminder(.:format)
{:controller=>"groups", :action=>"send_audit_reminder"}
However, I can't seem to figure out how to refer to the send_audit_reminder URL for a given route. I've tried send_audit_reminder_group_path(#group) and send_audit_reminder_url(#group), which both give me the following error:
No route matches {:controller=>"groups", :action=>"send_audit_reminder"}
As you can see from rake routes, there is indeed a route that matches those parameters, and there is also a matching method on the controller.
How can I find the path or URL for this route? I would like not to hard code it, since our apps are deployed to subdirectories on the same virtual host, so a hard-coded absolute path won't work.
And where would I look for documentation or information on this in the future? Since these path and URL helper methods are generated from my routes, I obviously can't look for documentation, and while rake routes tells me that the route is there, it doesn't appear to be there when I try and get the URL.
It might be that you're missing the placeholders and it can't route because of that. The following should work based on your definition:
send_audit_reminder_group_path(group)
Any time you see identifiers like :id or :group_id in your route, you must supply them unless they are in brackets, which declares them as optional, as is the case here with :format. The arguments need to be supplied in the same order they are declared. For this:
/example/:user_id/groups/:id
The arguments to this route would be user_id and id and both must be supplied. Generally with routes you can either use a literal number or string, or a model that supports to_param as all ActiveRecord::Base-derived ones do.
This all stems from declaring with :member, meaning it is specific to a particular record, and not :collection where that is omitted. The Rails Routing Guide explains more.