coneybeare
coneybeare

Reputation: 33101

Rails 3 Routes: Default format and also limited formats

I am having a problem combining 2 rails routing features (default params and param matching). Each is independently easy enough to solve, but when combined, the results are not quite what I am after.

The Rule:

get "/foobars(.:format)" => "foobars#index", :defaults => {:format => :json}, :format => /(xml|json)/

What I want:

  1. format param is optional
  2. if no format is included, default the format to json
  3. if format is included, ensure it is only xml or json
  4. if an unsupported format is passed, such as html, this route rule should not match.

What I am getting:

  1. format param is optional
  2. if no format is included, default the format to json
  3. if format is included, ensure it is only xml or json
  4. if an unsupported format is passed, such as baz, this route rule matches and sets the format to JSON.

The difference in point #4 is what I am trying to solve. In other words, I am after this:

GET /foobars      => "foobars#index"  with format `json`
GET /foobars.json => "foobars#index"  with format `json`
GET /foobars.xml  => "foobars#index"  with format `xml`
GET /foobars.baz  => "something#else" handled by another route rule lower down

What am I doing wrong here?

Upvotes: 2

Views: 1375

Answers (1)

quandrum
quandrum

Reputation: 1646

Have you tried making the last section a constraint?

get "/foobars(.:format)" => "foobars#index", :defaults => {:format => :json}, :constraints => {:format => /(xml|json)/}

Upvotes: 4

Related Questions