Param name and value (independantly) as part of Rails Route - ruby-on-rails

DocumentsController#common_query can handle multiple different request styles.
i.e. all docs in batch 4 or all docs tagged "happy"
I want a single route to make em pretty, so:
/documents/common_query?batch=4
/documents/common_query?tag=happy
become:
/documents/batch/4
/documents/tag/happy
So the end result is that #common_query is called but part of the url was used as the param name and part as it's value.

The second option, with two routes, is almost certainly the better way to go, because it will only match the kinds of URLs that you want to support, while the first option will also "match" URLs like /documents/foo/bar, which will likely cause your #common_query method to, at best, return a RecordNotFound (404) response. At worst, if you're not ready to not see any of your expected params, you'll get a 500 error instead...
Of course, if you start having a lot of variations, you end up with a lot of routes. And if you need to use them in combination, e.g., /documents/batch/4/tag/happy, then you'll need to use a wildcard route, and do the parameter processing in your controller. This might look something like:
map.connect 'documents/*specs', :controller => "documents_controller", :action => "common_query"
The various elements of the URL will be available your controller as params[:specs]. You might turn that into a find like so:
#items = Item.find(:all, :conditions => Hash[params[:specs]])
That Hash[] technique converts the one dimensional array of options into a key-value hash, which might be useful even if you're not feeding it directly to a find().

As a single route:
ActionController::Routing::Routes.draw do |map|
map.connect "documents/:type/:id", :controller => "documents_controller",
:action => "common_query"
end
Then params[:type] will either be "batch" or "tag", and params[:id] either "4" or "happy". You will have to make sure that other actions for the DocumentsController come before this in the routes because this will match any url that looks like "documents/*/*".
But why does it have to be a single route? You could use two routes like this:
map.with_options(:controller => "documents_controller",
:action => "common_query") do |c|
c.connect "documents/batch/:page", :type => "batch"
c.connect "documents/tag/:tag", :type => "tag"
end
which will have the same effect, but is more specific, so you wouldn't have to worry about the priority order of the routes.

Related

Multilingual routes - Advanced constraints not taken into consideration when paths are generated by url_for

I have a multilingual site in rails 3.2 that has some language-specific routes that map to the same action. Like:
For mydomain.fr
match "/bonjour_monde" => 'foo#bar'
For mydomain.de
match "/hallo_welt" => 'foo#bar'
To solve this I have used an advanced constraint when declaring the routes:
Application.routes.draw do
constraints(SiteInitializer.for_country("fr")) do
match "/bonjour_monde" => 'foo#bar'
end
constraints(SiteInitializer.for_country("de")) do
match "/hallo_welt" => 'foo#bar'
end
end
Where the SiteInitializer is just a class which responds to the matches? method and determines if the request is for the correct domain. This is actually only pseudo-code just demonstrating my setup.
class SiteInitializer
def initialize(country_code)
#country_code = country_code
end
def self.for_country(country_code)
new(country_code)
end
def matches?(request)
# based on the request, decide if this route should be declared
decide_which_country_code_from_request(request) == #country_code
end
end
This works fine. When requesting mysite.fr/bonjour_monde the app dispatches correctly and the paths are only bound to their specific domain.
mysite.fr/bonjour_monde => HTTP 200
mysite.fr/hallo_welt => HTTP 404
mysite.de/bonjour_monde => HTTP 404
mysite.de/hallo_welt => HTTP 200
Now, all is fine unless you start using things like url_for(:controller => 'foo', :action => 'bar'). If you do this, the constraints are not taken into consideration. This results in that the generated path from rails (Journey class), will be arbitrary.
If I somewhere in any view use url_for, like
url_for(:controller => 'foo', :action => 'bar')
rails will choose any arbitrary declared route that matches the controller action, probably the first one declared, skipping to check any advanced constraint.
If the user visits mysite.de/hallo_welt, and the view does something like:
= url_for(:controller => 'foo', :action => 'bar', :page => '2')
The output might be
mysite.de/bonjour_monde?page=2
^
wrong language
Actually, I don't use url_for specifically in code, but some gems like kaminari (paginator) do this and that's why you might be limited in using libraries that use the standard helper methods when generating paths.
Now, I'm not so sure if the Journey class should take the request context into consideration. But how would you approach this kind of problem?

Handling ambiguous routes in Rails

Here's my dilemma: I have two types of routes which are semantically very different, and should go to different controllers.
ny/new-york/brooklyn/cleaners # should go to a list of cleaners for a neighborhood
ny/new-york/cleaners/mrclean # should go to an individual cleaner's page
Note that "brooklyn" and "cleaners" here are just examples. The app has many service types (e.g. "cleaner") and many neighborhoods, so it's impossible to hard-code a list of either into a regular expression and use that to distinguish the two routes.
Is it possible to involve an arbitrary method, which accesses ActiveRecord models, in the routing decision? I'm using Rails 2.3.8.
Edit : new answer with dynamic services
Looking at this blog entry it seems possible to use ActiveRecords in the routes.
Maybe you could do something like this :
service_names = Service.all.map(&:short_name) # assuming the property 'short_name' is the value used in urls
service_names.each do |service_name|
map.connect ':state/:city/#{service_name}/:company' :controller => ‘company’, :action => ‘show’ # to show the company's page
map.connect ':state/:city/:neighborhood/#{service_name}_finder' :controller => ‘company_finder’, :action => ‘find’ # to list the companies for the given service in a neighborhood
end
That should still prevent conflicts since the routes for a certain service is before a route for a neighborhood
Old bad answer
Can't you use the two following routes ?
map.connect ':state/:city/cleaners/:cleaner' :controller => ‘cleaners’, :action => ‘show’ # to show the cleaner's page
map.connect ':state/:city/:neighborhood/cleaners' :controller => ‘cleaner_finder’, :action => ‘find’ # to list the cleaners of a neighborhood
In your controller, you should be able to retrieve :state, :city and others value using params[:state], params[:city], etc.
Putting the :state/:city/cleaners/:cleaner on the first line should prevent ambiguity.

Using named routes vs. using url_for()

When should one use named routes vs. using url_for with a {:controller => "somecontroller", :action => "someaction"} hash?
Is one preferred over the other and why? Is one more maintainable or more efficient w.r.t. performance?
It might help to understand what named routes are doing.
Defining a Named route creates a wrapper around url_for providing the options required for the created route. Routing resources creates many named routes.
With that in mind, the overhead of calling a named route as opposed to url_for with the options needed is negligible. So if you're linking to a specific resource, named routes are the way to go. They're easier to read, type and maintain.
However, don't discount url_for. It has many creative uses thanks to the way it handles missing options. It is very useful when it comes to keeping views DRY that are used from multiple nested sources. Ie: when you have a blog_posts controller and posts_controller sharing the same views.
I strongly encourage you to read the url_for documentation. To help figure out where those places it makes sense to use url_for are.
I would prefer named routes as it's shorter and does the same thing.
named route is very neat.
map.with_options :controller => "company", :action => "show", :panel => "name" do |m|
m.company '/company/:action/:id/:panel'
end
Then you can call
company_url :id => 1
If you set up your routes and resources carefully, you shouldn't need any hash routes, only named ones (either built-in via map.resource or custom map.<something> ). Hash routes are useful, if you have to create links based on dynamic content. Something like:
link_to #post.title, :controller => (#user.is_admin ? 'admin/posts' : 'public/posts'), :action => 'show', :id => #post
(This is just a forced example, but you should get the gist of it :)

Ruby on Rails: Routing for a tree hierarchy of places

So we've got a legacy system that tracks places with IDs like "Europe/France/Paris", and I'm building a Rails facade to turn this into URLs like http:// foobar/places/Europe/France/Paris. This requirement is not negotiable, the number of possible levels in unlimited, and we can't escape the slashes.
Setting up routes.rb for http://foobar/places/Europe is trivial:
map.resources :places
...but http:// foobar/places/Europe/France complains "No action responded to Europe". I tried:
map.connect '/places/:id', :controller => 'places', :action => 'show'
...but this gives the same result, as apparently the :id ends at the first '/'. How do I make the ID cover anything and everything after the "places"?
Have a look at the Routing Guide for full documentation:
http://guides.rubyonrails.org/routing.html
Specifically section "4.9 Route Globbing".
But I think what you really want to do is declare your route like:
map.connect '/places/*id', :controller => 'places', :action => 'index'
Called with a URL like
/places/foo/bar/1
Yields a params[:id] => ["foo", "bar", "1"]
Which you could easily (re)join with "/" to yield the full string you want "foo/bar/1" (you will probably have to re-insert the leading slash manually.
That should get you going.
I tweaked Cody's answer above slightly to come up with this:
map.place '/places/*id', :controller => 'places', :action => 'show'
map.connect '/places/*id.:format', :controller => 'places', :action => 'show'
By using map.place instead of map.connect, Rails knows what resource we're dealing with and generated place_url, place_path etc helpers correctly.
Now, the 2nd line should work but doesn't thanks to the bug above, so here's a workaround for places_controller.rb that manually splits the ID and sets the format, defaulting to XML:
id, suffix = params[:id].join('/').split('.')
params[:format] = suffix ? suffix : "xml"

Validate no routing overlap when creating new resources in Ruby on Rails

I've got a RESTful setup for the routes in a Rails app using text permalinks as the ID for resources.
In addition, there are a few special named routes as well which overlap with the named resource e.g.:
# bunch of special URLs for one off views to be exposed, not RESTful
map.connect '/products/specials', :controller => 'products', :action => 'specials'
map.connect '/products/new-in-stock', :controller => 'products', :action => 'new_in_stock'
# the real resource where the products are exposed at
map.resources :products
The Product model is using permalink_fu to generate permalinks based on the name, and ProductsController does a lookup on the permalink field when accessing. That all works fine.
However when creating new Product records in the database, I want to validate that the generated permalink does not overlap with a special URL.
If a user tries to create a product named specials or new-in-stock or even a normal Rails RESTful resource method like new or edit, I want the controller to lookup the routing configuration, set errors on the model object, fail validation for the new record, and not save it.
I could hard code a list of known illegal permalink names, but it seems messy to do it that way. I'd prefer to hook into the routing to do it automatically.
(controller and model names changed to protect the innocent and make it easier to answer, the actual setup is more complicated than this example)
Well, this works, but I'm not sure how pretty it is. Main issue is mixing controller/routing logic into the model. Basically, you can add a custom validation on the model to check it. This is using undocumented routing methods, so I'm not sure how stable it'll be going forward. Anyone got better ideas?
class Product < ActiveRecord::Base
#... other logic and stuff here...
validate :generated_permalink_is_not_reserved
def generated_permalink_is_not_reserved
create_unique_permalink # permalink_fu method to set up permalink
#TODO feels really ugly having controller/routing logic in the model. Maybe extract this out and inject it somehow so the model doesn't depend on routing
unless ActionController::Routing::Routes.recognize_path("/products/#{permalink}", :method => :get) == {:controller => 'products', :id => permalink, :action => 'show'}
errors.add(:name, "is reserved")
end
end
end
You can use a route that would not otherwise exist. This way it won't make any difference if someone chooses a reserved word for a title or not.
map.product_view '/product_view/:permalink', :controller => 'products', :action => 'view'
And in your views:
product_view_path(:permalink => #product.permalink)
It's a better practice to manage URIs explicitly yourself for reasons like this, and to avoid accidentally exposing routes you don't want to.

Resources