【问题标题】:NoMethodError when calling model's included class methods from controller从控制器调用模型包含的类方法时出现 NoMethodError
【发布时间】:2014-07-18 02:52:10
【问题描述】:

所以我的模型之一包含三个包含方法

#app/models/foobar.rb
class Foobar
  include Paginate
  include Sort
  include Query
end

在我的控制器中,我调用其中一个:

#app/controllers/foobar_controller.rb
Foobar.query(params[:q])

但是得到:

NoMethodError (undefined method `query' for #<Class:0x00000101469400>):

我确保将它们包含在我的 application.rb 中:

#config/application.rb
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

这里是query.rb:

#lib/query.rb
module Query
  module ClassMethods
    def query params
      (...)
    end
  end

  def self.included(receiver)
    receiver.extend ClassMethods
  end
end

为什么Controller看不到Foobar有这些类方法?它没有这些类方法吗?当我包含类方法时,我错过了什么吗?

【问题讨论】:

  • 您的示例在我的计算机上按预期工作。尝试进一步减少问题,直到你有一个超级简单的例子。从模型调用时是否会出现同样的问题?如果简化::query方法(如def query; puts "foo"; end)会出现同样的问题吗?
  • 确实如此,我将进一步简化。也许首先要确保我可以从我的控制器调用它。感谢您为我检查。

标签: ruby-on-rails


【解决方案1】:

这很令人困惑,但我得到了它的工作。因此,当我将lib/query 更改为lib/queryable 以及include Queryable 时,它可以完美运行。分页和排序也有效。我一定在我的代码中的其他地方使用了 Query 这个词。

太糟糕了,解决方案没有更有趣,也没有更具体的原因:(

至少我在快乐的路上。

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多