我想在控制器中推斷一個裝飾器,所以我以正常方式生成一個裝飾器(rails g 裝飾器)并在控制器中推斷它。但是,當我使用 Postman 進行測驗時,出現錯誤:
Could not infer a decorator for Employers::Job.
錯誤資訊顯示我在控制器中的語法不正確(在哪里.decorate使用),我不知道我哪里出錯了。
我嘗試過更改書寫方式并顯式指定裝飾器@job = Api::V2::Employers::JobDecorator.find(params[:id]).decorate(
這是控制器的一部分:
class Api::V2::Employers::JobsController < Api::V2::Employers::BaseController
before_action :get_job, except: [:index, :create, :renew]
before_action :get_tags, only: [:create, :update]
before_action :get_address, only: :update
def show
@job = @employer.jobs.find(params[:id]).decorate
render json: @job
end
end
這是一開始的裝飾器:
class Api::V2::Employers::JobDecorator < Draper::Decorator
delegate_all
decorates_association :employer
def attributes
#somethings
end
end
更新 2
感謝評論中的建議,在我Api::V2::Employers::JobDecorator.decorate(@job)在控制器中使用后情況發生了變化,但出現了一個新錯誤。訊息說undefined method 'attributes' for nil:NilClass,來源是以下檔案中的一行代碼:
#app/decorators/api/v2/employers/job_decorator.rb
class Api::V2::Employers::JobDecorator < Draper::Decorator
delegate_all
decorates_association :employer
def attributes
super.merge(
{
id: nil,
employer: nil,
}).delete_if { |k, v|
['class_name'].include?(k)
}
end
end
這是什么原因?
更新 3
按照評論的建議,在將一些裝飾器更改為以下內容后,我又回到了之前的錯誤。
def attrs
model.attributes.merge(
{
錯誤是“NoMethodError in Api::V2::Employers::JobsController#show”,指向的檔案是“config/initializer/active_model/serialization.rb”中的行之一(下面提取的最后一行):
module ActiveModel
module Serialization
def serializable_hash(options = nil)
options ||= {}
attribute_names = attributes.keys
uj5u.com熱心網友回復:
Draperinfers從被裝飾的物件中裝飾器,在您的場景中是Employers::Job.
因為您要使用的裝飾器具有完全不同的名稱,Api::V2::Employers::JobDecorator所以您需要明確指定它。
所以,Api::V2::Employers::JobDecorator.decorate(@job)是你需要的。
更多資訊,在這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/419426.html
標籤:
上一篇:RAILS呼叫`DidYouMean::SPELL_CHECKERS.merge!(error_name=>spell_checker)'已被棄用
