fxe
fxe

Reputation: 575

Get all nested resources records

I have to following model

User
has_many :threads
....

Thread
belongs_to :user
has_many :posts
....    

Post
belongs_to :thread
....

To get all Threads from a user i can just User.find( params[:id]).threads How can i get all posts from a user ?

Upvotes: 2

Views: 563

Answers (2)

Chris Lewis
Chris Lewis

Reputation: 1325

User
has_many :threads
has_many :posts, :through => :threads
....

Thread
belongs_to :user
has_many :posts
....    

Post
belongs_to :thread

Then you should be able to do:

user = User.first
user.posts

Upvotes: 2

railsdog
railsdog

Reputation: 1501


class User
  has_many :threads
  has_many :posts, :through => :threads
end

User.find(params[:id]).posts

should do the trick unless I'm dain-bramaged this morning.

Upvotes: 4

Related Questions