0

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?

GSto
  • 41,512
  • 37
  • 133
  • 184

2 Answers2

2

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.

Noz
  • 6,216
  • 3
  • 47
  • 82
  • By convention, I've always used `find_company`, but yes, this is the way to go. `get_company` will raise a 404 error if you try to route to an invalid company, which is exactly what you would expect from the client's point of view. – user229044 Jan 24 '13 at 20:20
0

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? )

Community
  • 1
  • 1
Rodrigo_at_Ximera
  • 548
  • 1
  • 7
  • 9