Reputation: 17793
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 ?
Upvotes: 9
Views: 2574
Reputation: 7899
One solution could be to use a before filter on your controller, like:
before_filter :load_user
def load_user
@user = User.find(params[:user_id]) if params[:user_id]
@posts = @user ? @user.posts : Post.all
end
Then you have to rewrite your controller a bit to function properly.
No refactoring needed on index
action, @posts
already loaded correctly, but you can do further filtering as you like
def index
@posts = @posts.where('updated_at < ?' Time.now)
end
Then update every member action: new, create, show, edit, update, destroy and use posts as a base like:
def new
@post = @posts.build
end
def create
@post = @posts.build(params[:task])
end
def show
@post = @posts.find(params[:id])
end
def edit
@post = @posts.find(params[:id])
end
def update
@post = @posts.find(params[:id])
end
def destroy
@post = @posts.find(params[:id])
end
Of course you can add other before filters to remove duplicate code.
Upvotes: 7
Reputation: 96454
Check the params.
If just post you'll just have :id
If user/post you'll have user and ID for post.
So check if params[:user]
...
n.b. If not user, try params[:user_id]
As for the index
method for posts
I think it will actually be the SAME in both cases. What will change things is its usage, association and scoping within user.
Upvotes: 1