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

Viewed 47

I've got two models with ActiveAdmin panels:

class Portfolio < ApplicationRecord
  has_many :portfolio_reports
end

class PortfolioReport < ApplicationRecord
  belongs_to :portfolio
end

Inside the Portfolio panel I would like to have a button that would create PortfolioReport for this Portfolio (it would take Admin to new PortfolioReport view with given portfolio_id basically).

To do so I've got below code:

# 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

Which gives me an error:

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

What did I missed?

1 Answers

Maybe this will help someone - the problem was on the wrong defined input form key. Inside of action_item I passed 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

and that's the key ActiveAdmin expected:

# 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

It's still weird that you can't pass an entire object as a params inside of link_to path e.g. new_admin_portfolio_report_path(resource). ActiveAdmin DSL can't handle it.

Related