0

我有属于用户的作者实体。用户 has_many 帖子。请建议我如何在用户的作者实体上显示最近的帖子。

class User < ActiveRecord::Base
  has_many :posts, :foreign_key => "author_id"
end

class Post < ActiveRecord::Base
  attr_accessible :title, :content
  belongs_to :author, :class_name => "User"
end

class Author < ActiveRecord::Base
  belongs_to :user
  has_many :recent_posts, :through => :user,
          :class_name => "Post",
          :limit => 3,
          :order => "updated_at desc"
end

最近的帖子应该怎么做?原始的sql?

4

1 回答 1

1

您希望使用 to:source选项来has_many指定另一个模型上的关联,如下所示:

has_many :recent_posts, :through => :user, :source => :posts, :limit => 3, :order => 'updated_at desc'
于 2013-01-22T21:28:46.353 回答