【问题标题】:How can I post data to rails backend in Association has_and_belongs_to_many?如何在 Association has_and_belongs_to_many 中将数据发布到 Rails 后端?
【发布时间】:2018-01-22 10:18:34
【问题描述】:

如下 我创建了与两个表的关联。

我在控制台添加的数据是:

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 => [])

还是不行

【问题讨论】:

  • 路线是什么。你在某处调用了create 操作吗?
  • @HaseebEqx 我已添加

标签: ruby-on-rails associations ruby-on-rails-5 postman


【解决方案1】:

因为您在允许其他人之前放置了params.require(:deal),所以rails 只接受:deal 下的参数。所以输入数据必须是

{"deal": {"shop_id": 1, "items": "items2", "customer_ids": "uuid"}}

或者您可以尝试直接允许其他值,例如

params.permit(:items, :shop_id, :customer_ids => [])

【讨论】:

  • 可能我的表达方式有误。就我而言,{"shop_id":1, items: "items2"} 插入了数据库,但只有{customer_id: "uuid"} 没有,所以我不明白为什么。
  • 还将内容类型设置为 application/json
  • 见鬼,成功了,但是私下的代码应该是params.permit(:items, :shop_id, :customer_ids=>[])
【解决方案2】:
{"deal" => {"shop_id" => 1, "items" => "items2", "customer_ids" => "uuid"}}

在您的控制器的私人操作中需要deal,所以在这里您需要将数据发送到deal 的包装器作为散列

params.require(:deal).permit(:items, :shop_id, :customer_ids)

【讨论】:

    【解决方案3】:

    试试这个:

    params.require(:deal).permit(:items, :shop_id, customer_ids: [])
    

    你在做什么样的关系?有很多结果吗?有很多?有吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-28
      • 2018-02-21
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      相关资源
      最近更新 更多