0

我正在学习 Rails 中的范围,并且在进行一些范围定义时遇到了一些麻烦。说我有以下型号..

class Category < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :post
end

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

class Comment < ActiveRecord::Base
  belongs_to :post
  has_many :categories, :through => :post
  # attribute: owner
end

注意 Comment 的属性所有者。我正在尝试编写一个范围,它将返回只有我通过的所有者发表的评论的类别。因此,如果一个类别有评论并且这些评论是由其他几个所有者发表的,则不应包含这些评论。我有这个工作。我得到的类别与我通过的所有者有评论..但我也得到其他所有者也有评论的类别。

在我的类别模型中,我有这个..

scope :comments_by_owner, lambda { |name| joins(:comments).where("comments.owner = ?", name) }

我打电话使用

Category.comments_by_owner("tom")

我试着玩 joins 和 uniq 但没有运气..

4

2 回答 2

1

尝试这个:

scope :comments_by_owner, lambda { |name| joins(:posts => :comments).where(:comments => {:owner => name})
于 2013-04-11T23:44:35.767 回答
0

看来,select用一个块使用Array#select. 尝试遍历所有类别,选择不包含其他名称注释的类别。

def find_single_name_categories(name)
  Category.scoped.select do |category|
    category.comments.scoped.select { |comment| comment.name != name }.empty?
  end
end
于 2013-04-16T00:44:42.947 回答