首页 > 解决方案 > Ruby 强参数:Integer 的 NoMethodError 未定义方法允许

问题描述

我的控制器:

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
})

标签: rubystrong-parameters

解决方案


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

也许您可以尝试(未测试):

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

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


推荐阅读