我在Rails API项目中使用ActiveModelSerializers
gem。
由于API版本控制,我在JobsController
内创建了一个app/controllers/v1/jobs_controller.rb
。
由于API版本控制,我还在JobSerializer
内创建了一个app/serializers/v1/job_serializer.rb
。
当我尝试像这样访问控制器内部的V1::JobSerializer
时:
def today_jobs
todays_jobs = Job.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).all.order('created_at DESC').page(params[:page] ? params[:page].to_i : 1).per(10)
render json: {objects: ActiveModel::Serializer::CollectionSerializer.new(todays_jobs, each_serializer: V1::JobSerializer), meta: pagination_meta(todays_jobs)}
end
不要介意分页,这一部分很重要:
objects: ActiveModel::Serializer::CollectionSerializer.new(todays_jobs, each_serializer: V1::JobSerializer)
[当我尝试返回此内容时会说uncaught throw :no_serializer
,因为我认为它不知道V1::JobSerializer
是什么。
只需确保:jobs_controller.rb
的定义如下:
class V1::JobsController < ApplicationController
end
[job_serializer.rb
的定义如下:
class V1::JobSerializer < ActiveModel::Serializer
end
我应该怎么做才能在我的作业控制器中访问V1::JobSerializer
?
范围嵌套运算符::
在声明嵌套的类/模块时绝对不要使用。始终使用显式嵌套:
# Bad:
class V1::JobsController < ApplicationController
puts JobSerializer.inspect # missing constant error
end
class V1::JobSerializer < ActiveModel::Serializer
end
# Good:
module V1
class JobsController < ApplicationController
puts JobSerializer.inspect # resolves to V1::JobSerializer
end
end
module V1
class JobSerializer < ActiveModel::Serializer
end
end
为什么?因为当您使用范围解析运算符时,模块嵌套被解析到定义的位置。这会导致令人惊讶的持续查找:
A = "I'm in the main scope"
module B
A = "I'm in B"
end
class B::C
puts A # outputs "I'm in the main scope"
end