2013-01-22 17 views
0

我擁有belongs_to用戶的作者實體。用戶has_many帖子。請建議如何顯示來自用戶的作者實體的recent_posts。AR在父類中加入類

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?

回答

1

您希望:source選項has_many,您可以用指定的其他模型的關聯,就像這樣:

has_many :recent_posts, :through => :user, :source => :posts, :limit => 3, :order => 'updated_at desc'