2015-05-20 109 views
0

我正在通过创建博客来学习rails。我有3个模型作为类别,评论和帖子。如何获得评论属于特定职位?

我想得到的评论属于特定的职位。我怎么弄到的?

#model/post.rb 

class Post < ActiveRecord::Base 
    has_many :comments 
    belongs_to :category 

    def latestcomments 
    // 
    end 
end 

#model/comment.rb 

class Comment < ActiveRecord::Base 

    belongs_to :post 
end 


#model/category.rb 
    has_many :posts 

回答

1
post = Post.find(:id).includes(:comments) 

获得该职位

comments = post.comments 

在意见表的意见POST_ID列是指关系的赌注。帖子和评论表

+0

我想在模型中定义一个方法。 ''def latestcomments comments = post.comments return comments'' 我在做对吧? – user121212

+0

只需在方法中写入def latestcomments self.comments结束。 –

+0

为什么您要创建latestcomments方法来获取喜剧?您是否在该方法中添加其他条件? –

相关问题