Strong parameters require multiple

前端 未结 7 1617
广开言路
广开言路 2020-12-30 19:03

I\'m receiving a JSON package like:

{
  \"point_code\" : { \"guid\" : \"f6a0805a-3404-403c-8af3-bfddf9d334f2\" }
}

I would like to tell Rai

相关标签:
7条回答
  • 2020-12-30 19:41

    OK, ain't pretty but should do the trick. Assume you have params :foo, :bar and :baf you'd like to require all for a Thing. You could say

    def thing_params
      [:foo, :bar, :baf].each_with_object(params) do |key, obj|
        obj.require(key)
      end
    end
    

    each_with_object returns obj, which is initialized to be params. Using the same params obj you require each of those keys in turn, and return finally the object. Not pretty, but works for me.

    0 讨论(0)
  • 2020-12-30 19:41

    This question came up in my google search for a different case ie, when using a "multiple: true" as in:

    <%= form.file_field :asset, multiple: true %>
    

    Which is a totally different case than the question. However, in the interest of helping out here is a working example in Rails 5+ of that:

    form_params = params.require(:my_profile).permit({:my_photos => []})
    
    0 讨论(0)
  • 2020-12-30 19:42

    As of 2015 (RoR 5.0+) you can pass in an array of keys to the require method in rails:

    params.require([:point_code, :guid])

    http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require

    0 讨论(0)
  • 2020-12-30 19:47

    The solution proposed in Rails documentation (https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require) is:

    def point_code
      params.require(:point_code).permit(:guid).tap do |point_code_params|
        point_code_params.require(:guid) # SAFER
      end
    end
    
    0 讨论(0)
  • 2020-12-30 19:52

    Although a lot of these answers show you how to get what you're asking for, I would like to add to these answers and suggest that you use a before_action. If the required params are missing, require will automatically return a 400 error

    class SomeController < ApplicationController
      before_action :ensure_valid_params, only: :index
    
      def index
        # do your stuff
      end
    
    private
    
      def ensure_valid_params
        params.require(:some_required_param)
      end
    end
    
    0 讨论(0)
  • 2020-12-30 20:01

    require takes one parameter. So there is no way you can pass in multiple keys unless you override the require method. You can achieve what you want with some additional logic in your action:

    def action
      raise ActionController::ParameterMissing.new("param not found: point_code") if point_params[:point_code].blank?
      raise ActionController::ParameterMissing.new("param not found: guid") if point_params[:point_code][:guid].blank?
    
      <do your stuff>
    end
    
    def point_params
      params.permit(point_code: :guid)
    end
    
    0 讨论(0)
提交回复
热议问题