在 Active Admin 中创建记录时如何修复 RecordNotFound 错误?

How to fix RecordNotFound error when creating a record in Active Admin?

我有一个注册应用程序,它注册了一个 Participant,然后可以将它与其他参与者放在一个 Group 中。我正在使用 ActiveAdmin 将它们分配给组。

当我尝试使用活动管理员创建新组时出现以下错误:

"ActiveRecord::RecordNotFound in Admin::GroupsController#create" with this additional information: "Couldn't find all Participants with 'id': (0, 0) (found 0 results, but was looking for 2)"

我想可能是因为我还没有为我的模型生成控制器。但是,当 运行 生成控制器时,我收到此错误:

identical  app/controllers/groups_controller.rb
  route  get 'groups/index'
  route  get 'groups/show'
  route  get 'groups/update'
  route  get 'groups/edit'
  route  get 'groups/create'
  route  get 'groups/new'
  invoke  erb
  exist    app/views/groups
  identical    app/views/groups/new.html.erb
  identical    app/views/groups/create.html.erb
  identical    app/views/groups/edit.html.erb
  identical    app/views/groups/update.html.erb
  identical    app/views/groups/show.html.erb
  identical    app/views/groups/index.html.erb
  invoke  test_unit
  identical    test/controllers/groups_controller_test.rb
  invoke  helper
  The name 'GroupsHelper' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.

虽然我的应用程序文件夹包含所有必需的文件,因此我将 @group = Group.new 添加到 groups_controller

这是我的模型:

# participant.rb
class Participant < ApplicationRecord
  has_one :volunteer_detail, :dependent => :destroy, inverse_of: :participant
  accepts_nested_attributes_for :volunteer_detail,   :allow_destroy => :true

  has_one :student_detail, :dependent => :destroy, inverse_of: :participant
  accepts_nested_attributes_for :student_detail,   :allow_destroy => :true
  has_and_belongs_to_many :groups, join_table: :matchups

  validates :last_name, presence: true
  # validates :gender, inclusion: { in: %w(male female) }
  validates :phone, presence: true
end

# group.rb
class Group < ApplicationRecord
  has_and_belongs_to_many :participants, join_table: :matchups
end

这是我的组的活动管理资源文件:

ActiveAdmin.register Group do
  permit_params :description , participant_ids: []
  form do |f|       
    f.inputs 'Group Details' do
    f.input :description
    f.input :participant_ids, as: :check_boxes, collection: Participant.pluck_all(:first_name, :last_name, :gender, :role, :id )
  end
end

我正在寻找使用 ActiveAdmin 中的表单创建新的 Group 记录,它利用关联模型 Participant 中的记录。

目前我收到 RecordNotFound 错误。这可能是由于控制器的问题造成的,但我不确定如何解决在控制器生成过程中引起的问题,或者这是否就是问题所在。

如能深入了解我的问题,我们将不胜感激。

此问题与 GroupsController 无关。 ActiveAdmin 资源与它无关。问题出在 participant_ids 的输入中。如果检查生成的 html,您可以在选项中看到空白值。应该是:

f.input :participants, as: :check_boxes, collection: Participant.pluck(:first_name, :id )

在这种情况下,您将 first_name 作为标签,将 id 作为值,一切顺利。如果你想要一个复杂的标签(:first_name, :last_name, :gender, :role),你需要在Group模型中创建一个单独的方法:

def label_for_admin
  first_name + last_name + gender + role
end

f.input :participants, as: :check_boxes, collection: Participant.pluck(:label_for_admin, :id )