【问题标题】:cross model scoping - rails 3交叉模型范围 - rails 3
【发布时间】:2023-04-08 19:37:02
【问题描述】:

我想为所有没有 cmets 的帖子创建一个范围...我不明白如何在模型中(通过创建范围)检查我的帖子是否附有任何评论,因为只有评论似乎知道他们属于哪个帖子,而不是帖子知道评论属于它。

Post
has_many :comments

Comments
belong_to :post

(如果我错了,请阻止我。)

【问题讨论】:

    标签: ruby-on-rails-3 scope rails-models


    【解决方案1】:

    用sql

    Post.includes(:comments).where("comments.id is NULL")
    

    所以范围是

    scope :without_comments, includes(:comments).where("comments.id is NULL")
    

    但最好在这里使用counter_cachehttp://railscasts.com/episodes/23-counter-cache-column

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      相关资源
      最近更新 更多