我有作者实体,其属于用户。用户has_many帖子。请告知我如何在用户的作者实体上显示recent_posts。
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
应该如何使用recent_post?原始的SQL?
答案 0 :(得分:1)
您需要:source
has_many
选项,用于指定其他模型上的关联,如下所示:
has_many :recent_posts, :through => :user, :source => :posts, :limit => 3, :order => 'updated_at desc'