I’m working on a blog like application,
my user module has_many posts and the posts module belongs_to user
I want to access both users/:id/posts and posts/
routes.rb is something like this:
resources :users do
resources :posts
end
resources:posts
how can i know within the posts controller if its accessed directly (/posts) or through the nested route (/users/:id/posts) ?
for example, what should be the index method of the posts controller for doing the correct INDEX action for /users/:id/posts and for /posts
is there a better way for doing this ?
One solution could be to use a before filter on your controller, like:
Then you have to rewrite your controller a bit to function properly.
No refactoring needed on
indexaction,@postsalready loaded correctly, but you can do further filtering as you likeThen update every member action: new, create, show, edit, update, destroy and use posts as a base like:
Of course you can add other before filters to remove duplicate code.