【发布时间】:2012-02-26 07:47:22
【问题描述】:
我的控制器中有一个可以正常工作的查询,但我想为它设置一个范围。当我尝试这样做时,我得到一个未找到方法的错误。以下是详细信息...
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 中,我需要获得一组已发布的兄弟帖子,不包括@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)
为什么 Ancestor gem 的兄弟关系在我的控制器中可用,但在我的模型中不可用?如何将此查询转换为范围?
【问题讨论】:
标签: ruby-on-rails-3 activerecord scope