【问题标题】:Rails 3.1 - Problems transferring a controller query into a model scopeRails 3.1 - 将控制器查询转移到模型范围的问题
【发布时间】: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


    【解决方案1】:

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

    所以@postsiblingsPost 没有!

    您可以将其分解为实例方法,而不是定义范围:

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

    【讨论】:

    • 我希望 TextMate 能以某种方式在视觉上区分“self”是类相关还是实例相关。或者也许我只是不应该在午夜过后处理“思考问题”! :-) 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多