2011-09-09 95 views
1

我正在使用Ruby on Rails 3.0.10和我想“减去”两个ActiveRecord::Relation“实体”并且再次返回一个ActiveRecord::Relation。也就是说,我有两个ActiveRecord::Relation对象(@articles@articles_checked)和下面的代码:ActiveRecord ::关系问题

@unchecked_articles = @articles - @articles_checked 

# $ @unchecked_articles.class 
# => Array 

@unchecked_articles.method_call 
# raise a NoMethodError error (read above for more information). 

上面的代码,反正返回一个Ruby Array所以我不能 “玩”(使用whereorder,.. 。陈述),因为我通常与ActiveRecord::Relation。在控制台它会生成以下错误:

NoMethodError (undefined method 'method_call' for #<Array:0x000001063dd658>) 

我怎样才能检索ActiveRecord::Relation对象后,我作出了上述变化?或更好,有一种方法可以完成我想用@unchecked_articles检索的内容?

回答

0

我不知道你的模型看起来如何,但我建议定义一个文章范围。

Article < ActiveRecord::Base 
    scope :unchecked, where(:checked => false) 

    #or this, apologies for somewhat unefficient, but you already seem to have several queries 
    scope :unchecked2, lambda { |checked| where(["id not in (?)", checked.map(&:id)]) } 

end 

Article.unchecked 
Article.unchecked2(@unchecked_articles) 
2

使用scope

scope :unchecked, where("checked is FALSE") 

我做了一个假设,有你标志检查这样的文章。定义范围之后,您可以拨打Article.unchecked为您提供未检查文章的AR。