我正在构建一个Rails 5.0 API,并尝试在对象上运行print_it
类as_json
。 (我需要一个单独的方法将复杂的逻辑放入以后)
每当我测试它时,它都会出错:
NoMethodError (undefined method print_it for #<Class:0x007f7b7b092f20>):
在Model:project.rb
中class Project < ApplicationRecord
def print_it
self.as_json
end
end
在controller:projects_controller.rb
中class Api::V1::ProjectsController < Api::ApiController
def index
render json: Project.print_it
end
end
如何在对象上使用print_it
?
答案 0 :(得分:2)
Project.print_it
正在课程print_it
上调用Project
。但是,您将print_it
定义为实例方法,而不是类方法,此处:
class Project < ApplicationRecord
def print_it
self.as_json
end
end
你可能想要更像的东西:
class Api::V1::ProjectsController < Api::ApiController
def index
render json: @project.print_it
end
end
当然,您需要设置@project
。
要在名为print_it
的{{1}}上使用ActiveRecord_Relation
,您可以执行以下操作:
@projects
您最终会获得@projects.map{|p| p.print_it}
。
但是可能会很昂贵,具体取决于项目数量和array
的性质。
如何在对象上使用print_it?
您 '在对象上使用'(调用)print_it
。 print_it
是一个对象。就像Project
是一个对象一样。您恰好在未定义@project
的对象上调用print_it
(因此print_it
错误。)
我还要注意Jörg W Mittag希望说:
我是Ruby Purists之一,他们喜欢指出Ruby中没有类方法。但是,我完全没问题,通常使用术语类方法 ,只要所有各方都完全理解这是一种口语用法。换句话说,如果您知道没有类方法这样的东西,并且术语“类方法”只是“作为实例的对象的单例类的实例方法”的缩写
undefined method
“,那就没问题了。但除此之外,我只看到它阻碍了理解。
让所有各方充分理解, class method 这个术语在上面的口语中使用。