Rails ActiveAdmin link_to 里面的新模式不同 - ActiveRecord::AssociationTypeMismatch

Rails ActiveAdmin link_to new model inside different - ActiveRecord::AssociationTypeMismatch

我有两个带有 ActiveAdmin 面板的型号:

class Portfolio < ApplicationRecord
  has_many :portfolio_reports
end

class PortfolioReport < ApplicationRecord
  belongs_to :portfolio
end

Portfolio 面板内,我希望有一个按钮可以为这个 Portfolio 创建 PortfolioReport(基本上,它会让管理员进入新的 PortfolioReport 视图并给定 portfolio_id)。

为此,我得到了以下代码:

# admin/portfolios.rb
ActiveAdmin.register Portfolio do
  action_item :portfolio_report, only: :show do
    link_to 'Create Report', new_admin_portfolio_report_path(portfolio_id: portfolio.id)
  end
end

# admin/portfolio_reports.rb
ActiveAdmin.register PortfolioReport do
  permit_params :portfolio_id
  includes :portfolio

  form do |f|
    f.inputs :published_at
    tabs do
      tab 'Intro content' do
        f.inputs do
          input :portfolio, as: :hidden
          # other inputs
        end
      end
    end
  end

这给我一个错误:

ActiveRecord::AssociationTypeMismatch in Admin::PortfolioReportsController#create
Portfolio(#523620) expected, got "" which is an instance of String(#4100)

我错过了什么?

也许这会对某人有所帮助 - 问题出在错误定义的输入表单键上。在 action_item 我通过了 portfolio_id:

# admin/portfolios.rb
ActiveAdmin.register Portfolio do
  action_item :portfolio_report, only: :show do
    link_to 'Create Report', new_admin_portfolio_report_path(portfolio_id: portfolio.id)
  end
end

这就是 ActiveAdmin 预期的关键:

# admin/portfolio_reports.rb
      form do |f|
        f.inputs :published_at
        tabs do
          tab 'Intro content' do
            f.inputs do
              **input :portfolio_id, as: :hidden**
              # other inputs
            end

您不能将整个对象作为参数传递到 link_to 路径内,这仍然很奇怪,例如new_admin_portfolio_report_path(resource)。 ActiveAdmin DSL 无法处理它。