HAxxor
HAxxor

Reputation: 1174

How to get all the Posts from a User

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

Answers (3)

Petros Kyriakou
Petros Kyriakou

Reputation: 5343

another one line example is the following, add this to your index

@posts = User.find(params[:user_id]).posts

Upvotes: 3

Jeremy Baker
Jeremy Baker

Reputation: 4282

I wrote a longish answer to a related question that may be helpful:

https://stackoverflow.com/a/17911920/321583

Upvotes: 1

Suborx
Suborx

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

Related Questions