使用范围和关联在Rails 3中保持DRY

Clo*_*boy 2 scope ruby-on-rails associations arel ruby-on-rails-3

以下是相关事实:

  1. 每个topic has_many comments.

  2. Comment模型有一个scope被调用very_popular,我们将假装涉及比较它的几个列.

    def self.very_popular
      # lots of cool stuff
    end
    
    Run Code Online (Sandbox Code Playgroud)
  3. Topic模型有一个scope叫做exciting,其中包括所有topicsvery_popular comments.

3号是我被困的地方.以下结果导致缺少方法异常,并且听起来很可怜​​,我不知道还有什么可尝试的!

def self.exciting
  join(:comments).very_popular
end
Run Code Online (Sandbox Code Playgroud)

如何very_popularComment模型范围内重用模型中Topic的范围?

Ale*_*kov 6

您不能直接使用其他模型的范围.你可以做的是合并查询. Topic.joins(:comments).merge(Comment.very_popular)

Ryan在这里解释得很漂亮:http://railscasts.com/episodes/215-advanced-queries-in-rails-3