活动管理员,不能与父级同时创建嵌套资源

active admin, cannot create nested resource at the same time as the parent

在我的应用中,Invoice has_many Item。因此,在我的活动管理员 UI 中,我希望能够创建发票,同时创建其项目。

但我只能在 invoice 使用活动管理中的 Edit Invoice 按钮创建后添加 items。尝试将它们一起创建不会将我从 New Invoice 页面引导到任何地方。并且没有显示任何错误。有人可以帮我解决这个问题吗?

我的 app/admin/invoice.rb

中有以下表单结构
permit_params :paid, :due, :customer_id,
              items_attributes: [:price, :description, :invoice_id, :purchased_product_id]

form multipart: true do |f|
  f.inputs do
    input :customer
    input :due
    input :paid, as: :radio
  end
  f.inputs "Items" do
    f.has_many :items do |item|
      item.input :price
      item.input :description
      item.input :purchased_product
    end
  end
  f.actions
end

我在我的 Invoice 模型中添加了 accepts_nested_attributes_for 如下:

class Invoice < ActiveRecord::Base
  belongs_to :customer
  has_many :items

  accepts_nested_attributes_for :items, allow_destroy: true

  validates :customer, presence: true

我正在使用 Rails 4,并且 activeadmin '~> 1.0.0.pre1'

问题是在我的 Item 模型中处理我的验证。我的 Item 模型 class

中有以下验证规则
validates :price, :invoice, presence: true

这表示要创建 item,它必须连接 invoice。但是由于在 invoice 及其包含的 items 的创建过程中,invoice 尚未保存到数据库中。 items 找不到要连接的 invoice,验证失败。

通过删除 invoice 的存在验证解决了问题,改为

validates :price, presence: true