Katie M
Katie M

Reputation: 1131

Rails 4 - Routing & Namespaces?

Ok, so - What did I do wrong? I feel like I'm missing something very simple...

REQUESTS belongs to USER

USER has many REQUESTS

I'm logged in as current_user (id=3) and want to list my requests:

<%= link_to("My Requests", user_requests_path(current_user)) %>

That link goes to /users/3/requests, but it shows ALL requests, not just those belonging to me.... ???

routes.rb
    resources :users do
      resources :requests
    end

rake routes:
 user_requests GET      /users/:user_id/requests(.:format)     requests#index

Upvotes: 0

Views: 502

Answers (1)

coreyward
coreyward

Reputation: 80140

This isn't related to your routes, then, it's a scoping problem on your ActiveRecord query. You probably have something like the following in RequestsController:

def index
  @requests = Request.all
end

But what you need to have is something more like the following:

def index
  @requests = current_user.requests
end

If your Request resource can be accessed independently of users (i.e. there's a use-case for Request.all or /requests) you should actually do a separate namespaced controller (e.g. Users::RequestsController) to handle user-specific requests. Your routes will then need to specify the namespace for the user-specific requests as well.

Upvotes: 1

Related Questions