【问题标题】:Ruby Strong Params: NoMethodError undefined method permit for IntegerRuby 强参数:Integer 的 NoMethodError 未定义方法允许
【发布时间】:2021-02-04 12:04:54
【问题描述】:

我的控制器:

class V1::SendContractController < V1::BaseController

  def create
    byebug
    bride_membership = Wedding.find(send_params[:weddingId]).bride_memberships[0]
    SendBrideContractJob.perform_now(bride_membership, send_params[:contractId])
    render json: { enqueuedDelivery: true }, status: :ok
  end

  private

  def send_params
    params
      .require(:weddingId)
      .permit(:contractId)
  end

end

我的参数

Parameters: {"weddingId"=>4, "contractId"=>20, "send_contract"=>{"weddingId"=>4, "contractId"=>20}}

错误

NoMethodError (undefined method `permit' for 4:Integer):

但是当我byebug它时,我得到了我想要的!

(byebug) params
<ActionController::Parameters {"weddingId"=>4, "contractId"=>20, "controller"=>"v1/send_contract", "action"=>"create", "send_contract"=>{"weddingId"=>4, "contractId"=>20}} permitted: false>
(byebug) params[:weddingId]
4

我正在使用axios 和拦截器来处理格式问题:

axios.interceptors.request.use((config) => {
  if(config.url !== "/authentications") {
    config.paramsSerializer = params => {
      // Qs is already included in the Axios package
      return qs.stringify(params, {
        arrayFormat: "brackets",
        encode: false
      });
    };
    axios.defaults.headers.common['Authorization'] = `Bearer ${store.state.token.token}`
    config.headers.common['Authorization']= `Bearer ${store.state.token.token}`
    axios.defaults.headers.common['Accept'] = 'application/vnd.bella.v1+json'
    config.headers.common['Accept'] = 'application/vnd.bella.v1+json'
    return config
  }
  return config
})

【问题讨论】:

    标签: ruby strong-parameters


    【解决方案1】:

    我相信 require 会为您提供您提供的密钥对象,以进行进一步的 permit 和/或 require 调用。

    也许你可以试试(未测试):

    params.require(:weddingId)
    params.permit(:weddingId, :contractId)
    

    编辑:还有这个:Multiple require & permit strong parameters rails 4

    【讨论】:

      【解决方案2】:

      请参阅此documentationquestionrequire 确保存在参数。如果存在,则返回给定键的参数,否则引发ActionController::ParameterMissing error

      p =  { "weddingId"=>4, "contractId"=>20 }
      
      ActionController::Parameters.new(p).require(:weddingId)
      # 4
      
      p = { "weddingId"=>nil, "contractId"=>20 }
      
      ActionController::Parameters.new(p).require(:weddingId)
      # ActionController::ParameterMissing: param is missing or the value is empty: weddingId
      

      如果您想确保:weddingId 存在:

      def contract_params
          params.require(:weddingId)
          params.permit(:contractId, :weddingId)
      end
      
      

      顺便说一句,SendContractController 最好称为ContractsController

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 2023-03-06
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多