Rails关联和范围

时间:2013-04-11 22:39:55

标签: ruby-on-rails

我正在学习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")

我试过玩连接和uniq但没有运气..

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分: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
相关问题