获取所有嵌套资源记录

时间:2012-11-21 15:40:46

标签: ruby-on-rails ruby activerecord

我必须遵循模型

User
has_many :threads
....

Thread
belongs_to :user
has_many :posts
....    

Post
belongs_to :thread
....

要获取用户的所有主题,我可以User.find( params[:id]).threads 我怎样才能收到用户的所有帖子?

2 个答案:

答案 0 :(得分:4)


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

User.find(PARAMS [:ID])。帖子

除非我今天早上受到严重的伤害,否则

应该做到这一点。

答案 1 :(得分:2)

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

Thread
belongs_to :user
has_many :posts
....    

Post
belongs_to :thread

然后你应该能够做到:

user = User.first
user.posts