dry-rb / dry-rails

The official dry-rb railtie
https://dry-rb.org/gems/dry-rails
MIT License
270 stars 27 forks source link

safe_params are empty in ApplicationController before_action #25

Closed HolyWalley closed 4 years ago

HolyWalley commented 4 years ago

Describe the bug

# frozen_string_literal: true

class UsersController < ApplicationController
  before_action do
    if safe_params&.failure?
      head 422
    else
      head 200
    end
  end

  schema(:show) do
    required(:id).value(:integer)
  end

  def show
  end
end

This code will always return 200, because:

lib/dry/rails/features/safe_params.rb

def schema(*actions, &block)
  schema = Dry::Schema.Params(&block)

  actions.each do |name|
    schemas[name] = schema
  end

  before_action(:set_safe_params, only: actions)

  self
end
before_action(:set_safe_params, only: actions)

this before_action is put in queue after before_action in UsersController. This might not be a problem in UsersController, I can just move my before_actions bellow the schema definition, however, if I'm trying to do something like here: https://dry-rb.org/gems/dry-rails/0.1/#safe-params and provide params check in ApplicationController I'll face the problem when I always get nil by calling safe_params.

To Reproduce

Use the code above

Expected behavior

safe_params is available in any callback

Your environment