【问题标题】:undefined local variable or method `permitted_task_attributes’ for #<Api::V1::TasksController#<Api::V1::TasksController 的未定义局部变量或方法“permitted_task_attributes”
【发布时间】:2021-04-16 11:30:28
【问题描述】:

我有一个遵循 Spree/Solidus 范例的解决方案,它封装了允许的参数。我没有能力改变它,而是效仿。但是,我遇到了一个问题,我无法重现 #Api::V1::TasksController:0x0000000000b7c0 的未定义局部变量或方法“permitted_task_attributes”。

下面是代码:

controller/api/v1/task_controller.rb

module Api
  module V1
    class TasksController < ApiController
      def index
        task = Task.all
        render json: task
      end

      def create
        task = Task.create!(create_action_params)
        if task
          render json: task
        else
          render json: task.errors
        end
      end

      private

      def create_action_params
        params.require(:task).permit(permitted_task_attributes) # The problem is with this variable `permitted_task_attributes`
      end
    end
  end
end

controller/api_controller.rb

class ApiController < ApplicationController
  before_action :set_api_request

  private

  def set_api_request
    request.format = request.format == :xml ? :xml : :json
  end
end

lib/controller_helpers/strong_parameters.rb

module ControllerHelpers
  module StrongParameters
    def permitted_attributes
      PermittedAttributes
    end

    delegate(*PermittedAttributes::ATTRIBUTES,
             to: :permitted_attributes,
             prefix: :permitted)

    def permitted_task_attributes
      permitted_attributes.task_attributes
    end
  end
end

lib/permitted_attributes.rb

module PermittedAttributes
  ATTRIBUTES = [
    :task_attributes
  ].freeze

  mattr_reader(*ATTRIBUTES)

  @@task_attributes = [
    :avatar_url, :description, :recorded_on
  ]
end

错误

undefined local variable or method `permitted_task_attributes’ for #<Api::V1::TasksController:0x0000000000b7c0>

我知道控制器无法访问这个名为 permitted_task_attributes 的方法,但我无法修复它。我试图在控制器中包含ControllerHelpers::StrongParameters,但我仍然有未初始化的常量错误。我该如何解决这个问题?

【问题讨论】:

  • /lib自 Rails 3 或类似版本以来未包含在自动加载路径中。要么需要文件,要么将其放在自动加载的/app 中。

标签: ruby-on-rails spree ruby-on-rails-6 solidus spree-auth-devise


【解决方案1】:

因此,我已将 strong_parameters.rb/lib 中移出并将其移至控制器问题。我也将 permitted_atrributes.rb 移出了/lib 目录。然后我将 strong_parameters.rb 包含在 tasks_controller.rb 中,例如include StrongParameters.

问题是控制器无法识别 strong_parameters.rb 中的permitted_task_attributes 方法并引发错误。

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2018-04-19
    • 2015-01-01
    • 2013-12-17
    • 2016-04-29
    • 2018-04-21
    相关资源
    最近更新 更多