在Active Admin中创建记录时,如何解决RecordNotFound错误?

时间:2019-01-31 23:33:50

标签: ruby-on-rails activerecord activeadmin

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

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

  

“ Admin :: GroupsController#create中的ActiveRecord :: RecordNotFound”与   这些附加信息:“找不到具有以下内容的所有参与者   'id':( 0,0)(找到0个结果,但正在寻找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错误。这可能是由于控制器的问题引起的,但是我不确定如何解决在控制器生成过程中引起的问题,或者甚至是问题所在。

任何对我的问题的见解将不胜感激。

1 个答案:

答案 0 :(得分:1)

该问题与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),则需要在组模型中创建单独的方法:

def label_for_admin
  first_name + last_name + gender + role
end

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