Reputation: 1174
I have a User and Post scaffolded in my rails application. I wanted to get all of the posts associated with a user. For example, I want to be able to do something like this:
localhost:3000/users/1/posts
And it should give me all of the posts with the user_id = 1. I know how to get all the posts via the rails console for a specific user. I was just wondering how i can accomplish something like the example above. Would I have to add another method in the users controller?
Upvotes: 1
Views: 3991
Reputation: 5343
another one line example is the following, add this to your index
@posts = User.find(params[:user_id]).posts
Upvotes: 3
Reputation: 4282
I wrote a longish answer to a related question that may be helpful:
https://stackoverflow.com/a/17911920/321583
Upvotes: 1
Reputation: 3669
You can do it without adding new action. Like this:
class PostsController < ApplicationController
def index
@user = User.find(params[:user_id])
@posts = @user.posts
end
end
Upvotes: 7