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

423 views Asked by At

I have a solution that follows the paradigm of Spree/Solidus, which encapsulate permitted params. It is not in my power to change it but to follow suit. However, I am having a problem I cant reproduce which is undefined local variable or method `permitted_task_attributes’ for #Api::V1::TasksController:0x0000000000b7c0.

Below is the code:

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_atrributes.rb

module PermittedAttributes
  ATTRIBUTES = [
    :task_attributes
  ].freeze

  mattr_reader(*ATTRIBUTES)

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

Error

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

I do understand the controller do not have access to this method called permitted_task_attributes but I couldn't fix it. I have tried to include ControllerHelpers::StrongParameters in the controller and I still have uninitialized constant error. How can I fix this?

1

There are 1 answers

0
Afolabi Olaoluwa On BEST ANSWER

So, I have moved strong_parameters.rb out of /lib and moved it to controller concerns. I alos moved permitted_atrributes.rb out of /lib directory too. I then include strong_parameters.rb in the tasks_controller.rb e.g. include StrongParameters.

The problem is that the controller didn't recognize the permitted_task_attributes method in the strong_parameters.rb and it throws an error.