Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 有了rails,我如何找到不在Has Many Through集合中的对象?_Ruby On Rails - Fatal编程技术网

Ruby on rails 有了rails,我如何找到不在Has Many Through集合中的对象?

Ruby on rails 有了rails,我如何找到不在Has Many Through集合中的对象?,ruby-on-rails,Ruby On Rails,假设一篇文章通过标记有许多标记 Article has_many :taggings has_many :tags, :though :taggings end @article.tags#给出该文章的所有标签 如何找到本文没有的所有标记 谢谢我能想到的使用Rails Finder实现这一点的唯一方法是执行两个查询并减去: class Article def unused_tags Tag.all - self.tags end end 或者,您可以通过SQL来实

假设一篇文章通过标记有许多标记

Article
   has_many :taggings
   has_many :tags, :though :taggings
end
@article.tags#给出该文章的所有标签

如何找到本文没有的所有标记


谢谢

我能想到的使用Rails Finder实现这一点的唯一方法是执行两个查询并减去:

class Article
  def unused_tags
    Tag.all - self.tags
  end
end
或者,您可以通过SQL来实现这一点(这将更加高效,因为您将只获得所需的行):


query=以下是我的想法:

 class Article
    def missing_tags
       Tag.find(:all, :conditions => ['id NOT IN (SELECT taggings.tag_id FROM taggings WHERE (taggings.article_id = ?))', self.id])
    end
 end

@article.missing_tags

我使用这种方法作为集合的一部分,因此我的代码看起来像Tag.all-@instance_article.tags
 class Article
    def missing_tags
       Tag.find(:all, :conditions => ['id NOT IN (SELECT taggings.tag_id FROM taggings WHERE (taggings.article_id = ?))', self.id])
    end
 end