GSto
GSto

Reputation: 42350

ruby on rails: how to restrict nested routes?

I have a company model, and a company can have many locations, so I have routes set up like so:

resources :companies do
  resources :locations
end

I'd like to be able to add a new location to a company at the route companies/:company_id/locations/new , however this page is still accessible if I go to a company that does not exist, like so companies/99999999/locations/new.

How can I make this page only accessible when the company id exists?

Upvotes: 0

Views: 166

Answers (2)

Noz
Noz

Reputation: 6346

You can add a before_filter to your locations controller (you're going to need to retrieve the parent company anyways for nested forms and links):

class LocationsController < ApplicationController

  before_filter :get_company    

  def get_company
    @company = Company.find(params[:company_id])
  end   

end

This way navigating to a Location route under an erroneous Company ID will produce the typical id not found exception which you would normally see if it wasn't a nested resource. Typically you would handle this exception in your application controller and redirect to a 404 page.

Upvotes: 2

Rodrigo_at_Ximera
Rodrigo_at_Ximera

Reputation: 548

Not sure if you want something defined in routes.rb itself, but I'd just validate the existence of the company in the controller's action (and render a 404, if that's what you want, as explained in How to redirect to a 404 in Rails? )

Upvotes: 0

Related Questions