【问题标题】:Rails 5 Api create new object from json with nested resourceRails 5 Api使用嵌套资源从json创建新对象
【发布时间】:2019-04-19 23:37:13
【问题描述】:

这是从外部 angular webapp 作为参数接收的 json:

{
  "provincia": {
    "id": 1,
    "name": "Province"
  },
  "username": "tester",
  "direccion": "new avenue 100",
  "email": "nomail@mail.com"
}

这是我的控制器

 def create
   @seller = Seller.new(seller_params)

  if @seller.save
    render json: @seller, status: :created, location: @seller
  else
    puts @seller.errors.full_messages
    render json: @seller.errors, status: :unprocessable_entity
  end
end

这是卖家参数

def seller_params
    params.require(:seller).permit(:username, :direccion, :email, :provincia_id)
end

模型:卖家属于_to Provincia

服务器控制台输出错误完整消息

Provincia must exist

我应该对 Rails API 进行哪些修改才能使其正常工作并保存新卖家?提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby angular api ruby-on-rails-5


    【解决方案1】:

    您在控制器中允许参数的方式不正确:

    Rails Docs

    你需要在你的属性中传递你的 provincia_id 或者允许你传递给你的控制器的属性

    方式一:

    {
      "provincia_attributes": {
        "id": 1,
        "name": "Province"
      },
      "username": "tester",
      "direccion": "new avenue 100",
      "email": "nomail@mail.com"
    }
    

    SellersController.rb

    def seller_params
      params.require(:seller).permit(:username, :direccion, :email, provincia_attributes: [:id, :name])
    end
    

    方式 2

    {
      "provincia_id": "1"
      "username": "tester",
      "direccion": "new avenue 100",
      "email": "nomail@mail.com"
    }
    

    SellersController.rb

    def seller_params
      params.require(:seller).permit(:username, :direccion, :email, :provincia_id)
    end
    

    【讨论】:

    • 请注意,provincia_attributes 只会在 Seller accepts_nested_attributes_for :provincia 时动态创建嵌套记录。
    【解决方案2】:

    尝试像这样更改参数:

    def seller_params
      p = params.require(:seller).premit(:username, :direccion, :email).to_h
      p[:seller][:provincia_id] = params[:seller][:provincia][:id]
      p
    end
    

    这将添加您在关联中缺少的“provincia_id”键。我调用 to_h 来获取一个新的哈希值,因为我不喜欢改变原始参数并且你已经允许了你想要的值,所以哈希值可以安全使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2010-10-25
      • 2015-12-28
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      相关资源
      最近更新 更多