我如何 post 数据到关联 has_and_belongs_to_many 中的 rails 后端?
How can I post data to rails backend in Association has_and_belongs_to_many?
如下
我创建了两个表的关联。
我在控制台添加的数据是:
Deal.create(items: "items1", shop_id:1, customer_ids: "uuid")
成功了。
但是当我尝试使用邮递员进行测试时
{"shop_id": 1, "items": "items2", "customer_ids": "uuid"}
新数据客户是null
我的控制器:
def create
@deal = Deal.new(deal_params)
respond_to do |format|
if @deal.save
format.json { render :show, status: :created }
else
format.json { render json: @deal.errors, status: :unprocessable_entity }
end
end
end
def deal_params
params.require(:deal).permit(:items, :shop_id, :customer_ids)
end
我的路线:
post 'deals', to: 'deals#create'
日志没有发生错误。
我的问题是什么?
更新
我直接在我的控制器上尝试相同的数据
@deal = Deal.new({"shop_id": 1, "items": "items2", "customer_ids": "uuid"})
成功了...
所以我认为问题出在我的 deal_params 函数上
我试试教程
params.require(:deal).permit(:items, :shop_id, :customer_ids => [])
但还是不行
{"deal" => {"shop_id" => 1, "items" => "items2", "customer_ids" => "uuid"}}
在您的控制器的私人操作中需要 deal
因此您需要将数据作为散列
发送到 deal
的包装器
params.require(:deal).permit(:items, :shop_id, :customer_ids)
因为您在允许其他 rails 之前放置 params.require(:deal)
仅在 :deal
下获取参数。所以输入数据必须是
{"deal": {"shop_id": 1, "items": "items2", "customer_ids": "uuid"}}
或者您可以尝试直接允许其他值,例如
params.permit(:items, :shop_id, :customer_ids => [])
试试这个:
params.require(:deal).permit(:items, :shop_id, customer_ids: [])
你是什么关系?有很多trust?有很多?有吗?
如下 我创建了两个表的关联。
我在控制台添加的数据是:
Deal.create(items: "items1", shop_id:1, customer_ids: "uuid")
成功了。
但是当我尝试使用邮递员进行测试时
{"shop_id": 1, "items": "items2", "customer_ids": "uuid"}
新数据客户是null
我的控制器:
def create
@deal = Deal.new(deal_params)
respond_to do |format|
if @deal.save
format.json { render :show, status: :created }
else
format.json { render json: @deal.errors, status: :unprocessable_entity }
end
end
end
def deal_params
params.require(:deal).permit(:items, :shop_id, :customer_ids)
end
我的路线:
post 'deals', to: 'deals#create'
日志没有发生错误。
我的问题是什么?
更新
我直接在我的控制器上尝试相同的数据
@deal = Deal.new({"shop_id": 1, "items": "items2", "customer_ids": "uuid"})
成功了...
所以我认为问题出在我的 deal_params 函数上
我试试教程
params.require(:deal).permit(:items, :shop_id, :customer_ids => [])
但还是不行
{"deal" => {"shop_id" => 1, "items" => "items2", "customer_ids" => "uuid"}}
在您的控制器的私人操作中需要 deal
因此您需要将数据作为散列
deal
的包装器
params.require(:deal).permit(:items, :shop_id, :customer_ids)
因为您在允许其他 rails 之前放置 params.require(:deal)
仅在 :deal
下获取参数。所以输入数据必须是
{"deal": {"shop_id": 1, "items": "items2", "customer_ids": "uuid"}}
或者您可以尝试直接允许其他值,例如
params.permit(:items, :shop_id, :customer_ids => [])
试试这个:
params.require(:deal).permit(:items, :shop_id, customer_ids: [])
你是什么关系?有很多trust?有很多?有吗?