【问题标题】:How to use model scopes in a custom module?如何在自定义模块中使用模型范围?
【发布时间】:2013-08-24 16:43:22
【问题描述】:

在我的模型中,我已经定义了范围:

class MyModel < ActiveRecord::Base
  scope :accessible_for, ->(user) { where(user_id: user.id) }
end

在控制器中完美运行:

class MyController < ActionController::Base

  def index
    @operations = MyModel.accessible_for current_user
  end

end

我想在自定义模块中使用它

module Reports
  class ReportMyModel

    def do_export(user)
      to_export = MyModel.accessible_for user
    end

  end
end

不幸的是,我在调用“do_export”后收到一个错误

undefined method `accessible_for' for <Class:0x000000065396d8>

那么,如何正确使用呢?

【问题讨论】:

  • 您的作用域被命名为accesible_for,并带有一个s。你有一个错字!
  • 哦,这只是一个错字!范围定义为范围 :accessible_for, ->(user) { where(user_id: user.id) }
  • 另外,当我从 Rails 控制台调用 do_export 时,它可以正常工作...

标签: ruby-on-rails activerecord scope


【解决方案1】:

在另一个工作站上成功运行此代码后,我重新启动了计算机,一切都变得很好。所以,代码没有任何错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2013-01-06
    相关资源
    最近更新 更多