【问题标题】:Wrong number of arguments (given 2, expected 1)参数数量错误(给定 2,预期 1)
【发布时间】:2018-12-02 05:10:33
【问题描述】:

我在尝试创建关系对象成分测量时出错,这是我的控制器:

 module Api
  module V1
    class IngredientMeasuresController < ApplicationController

    def index
      render json: IngredientMeasure.all
    end

    def create
      ingredient_measure = IngredientMeasure.new(params[:ingredient_id, :measure_id])
      if ingredient_measure.save
        render json: ingredient_measure
      else
        render json: {status: 500, err: 'Ingredient measure could not be created'}
      end
    end
    private

    def ingredient_measure_params
      params.require(:ingredient_measure).permit(:ingredient_id, :measure_id)
     end
   end
 end
end

当我发布这样的内容时

{       
    "measure_id" : 3,
    "ingredient_id":3
}

它给了我wrong number of arguments (given 2, expected 1) 错误,即使我的模型有这两个字段,因为我可以通过 rails 控制台而不是控制器创建它们,如果我使用

ingredient_measure = IngredientMeasure.new(ingredient_measure_params)

在第 10 行,我收到 param is missing or the value is empty: ingredient_measureerror

这是我在架构中的模型

create_table "ingredient_measures", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "ingredient_id"
t.bigint "measure_id"
t.index ["ingredient_id"], name: "index_ingredient_measures_on_ingredient_id"
t.index ["measure_id"], name: "index_ingredient_measures_on_measure_id"
end

【问题讨论】:

  • 尝试使用IngredientMeasure.new(ingredient_measure_params) + 使用fetch 而不是require 作为您的许可参数:params.fetch(:ingredient_measure, {}).permit(:ingredient_id, :measure_id)

标签: ruby-on-rails json ruby ruby-on-rails-5


【解决方案1】:

这不是您将参数传递给ActiveRecord 模型的方式。 应该是:

ingredient_measure = IngredientMeasure.new(ingredient_measure_params)

您收到此错误的确切原因是您尝试在 params 返回的类哈希结构上调用 [] 方法,并带有两个参数 ([:ingredient_id, :measure_id]),这显然没有意义。如果您遇到过[] 运算符,通常可以安全地假定它只需要一个参数。

【讨论】:

  • 当我这样做时,它会抛出我ParameterMissing: param is missing or the value is empty: ingredient_measure
【解决方案2】:

我在邮递员中取消了我发布数据的地方的 Content-type application/json 选项

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多