2012-02-26 47 views
0

我在我的控制器中有一个查询可以正常工作,但我想将它作为一个范围。当我尝试这样做时,我得到一个未找到错误的方法。下面是详细信息...Rails 3.1 - 将控制器查询转移到模型范围中的问题

class Post 
    has_ancestry # part of a tree of posts, managed with the Ancestry gem 
    attr_accessible :body, :user_id, :published 
end 

posts_controller.rb我需要得到一组公布的兄弟的帖子,SAN的@post记录本身(其祖先包括“兄弟”的结果)。此代码工作正常:

def show 
    @post = Post.find(params[:id]) 
    @published_sibs = @post.siblings.where("id <> :id", :id => @post.id).where("published = :published", :published => true) 
end 

我尝试移动此查询到一个范围,我Post.rb文件是这样的:

class Post 
    has_ancestry # part of a tree of posts, managed withthe Ancestry gem 
    attr_accessible :body, :user_id, :published 
    scope :published_sibs, self.siblings.where("id <> :id", :id => self.id).where("published = :published", :published => true) 
end 

当我尝试加载Rails的,我得到:

... active_record/base.rb:1088:in `method_missing': undefined method `siblings' for #<Class:0x007fc3d4e33470> (NoMethodError) 

为什么祖先宝石的兄弟姐妹关系在我的控制器中可用,但不是我的模型中的范围?我怎样才能把这个查询翻译成一个范围?

回答

1

问题是您正在研究类Post的实例而不是类本身。

so @post has siblings but Post does not!

,而不是定义范围,你可以只因子它变成一个实例方法:

def published_sibs 
    siblings.where("id <> :id", :id => self.id).where("published = :published", :published => true) 
end 
+0

我希望的TextMate会在一定程度视觉上区分时,“自我”是与对实例相关的类。或者,也许我不应该在午夜过去时“思考问题”。 :-) 谢谢你的帮助。 – 2012-02-26 19:22:43