尝试创建关系对象Ingredient_measure时出现错误,这是我的控制器:
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_measure
错误
这是我在模式中的模型
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
答案 0 :(得分:0)
这不是将参数传递到ActiveRecord
模型中的方式。
应该是:
ingredient_measure = IngredientMeasure.new(ingredient_measure_params)
出现此错误的确切原因是,您尝试在[]
返回的具有两个参数(params
)的类似哈希的结构上调用[:ingredient_id, :measure_id]
方法,这显然没有用感。如果您遇到[]
运算符,通常可以安全地假设它只接受一个参数。
答案 1 :(得分:-1)
我在发布数据的邮递员中取消选中选项Content-type application / json