无法通过嵌套属性 Rails API 创建记录



我目前正在尝试创建一个订单实例。模型OrderItems相关联。关联如下。 Order有很多Items.我尝试按照文档 https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

class Order < ApplicationRecord
  has_many :items
  accepts_nested_attributes_for :items
end
class OrdersController < ApplicationController
  ##
  private
  def order_params
    params.require(:order).permit(:description,
                                  items_attributes: [:id, :quantity])
  end
end

从下面的帖子中,它表明必须在参数中传递 id。Rails 5 API 使用嵌套资源从 json 创建新对象

params = {order: {description: "this is a test"}, items_attributes: [{id: 3, quantity: 3, description: 'within order -> item'}]}
=> {:order=>{:description=>"this is a test"}, :items_attributes=>[{:id=>3, :quantity=>3, :description=>"within order -> item"}]}
[7] pry(main)> order_test = Order.create!(params[:order])
   (0.4ms)  BEGIN
  Order Create (62.9ms)  INSERT INTO "orders" ("description", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["description", "this is a test"], ["created_at", "2019-05-30 23:31:39.409528"], ["updated_at", "2019-05-30 23:31:39.409528"]]
   (4.6ms)  COMMIT
=> #<Order:0x00007ff91556e4b8 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>

我创建了一个订单,但是当我检查items时,它会返回一个空数组。

=> #<Order:0x00007ff9142da590 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>
[11] pry(main)> Order.last.items
  Order Load (0.4ms)  SELECT  "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT $1  [["LIMIT", 1]]
  Item Load (0.3ms)  SELECT "items".* FROM "items" WHERE "items"."order_id" = $1  [["order_id", 14]]
=> []

下表列出了项目:

class CreateItems < ActiveRecord::Migration[5.2]
  def change
    create_table :items do |t|
      t.references :order, foreign_key: true
      t.integer :quantity
      t.string :description
      t.timestamps
    end
  end
end

怎么了?

错误在于参数的传递顺序。

{:order=>{:id=>22, :description=>"this is a test", :items_attributes=>[{:order_id=>22, :quantity=>3, :description=>"within order -> item"}]}}

这解决了它:

order = Order.create!(params[:order])
<Order:0x00007ff918039ee0 id: 22, description: "this is a test", created_at: Fri, 31 May 2019 01:39:23 UTC +00:00, updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>
[39] pry(main)> order.items
  Item Load (114.8ms)  SELECT "items".* FROM "items" WHERE "items"."order_id" = $1  [["order_id", 22]]
=> [#<Item:0x00007ff9180394b8
  id: 4,
  order_id: 22,
  quantity: 3,
  description: "within order -> item",
  created_at: Fri, 31 May 2019 01:39:23 UTC +00:00,
  updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>]

最新更新