在ActiveAdmin中,当你尝试自定义操作来创建新记录时,可能会遇到“缺少必需键::id”的错误。这是因为在创建新记录时,还没有为该记录分配一个ID。以下是解决该问题的一种方法:
ActiveAdmin.register YourModel do
action_item :custom_action, only: :index do
link_to 'Custom Action', new_admin_your_model_path
end
collection_action :custom_action, method: :get do
# 创建一个新的记录
new_record = YourModel.new
# 保存新的记录
new_record.save
# 执行其他自定义逻辑
# 重定向回index页面
redirect_to admin_your_models_path, notice: 'New record created successfully.'
end
member_action :custom_action, method: :get do
# 创建一个新的记录
new_record = YourModel.new
# 保存新的记录
new_record.save
# 执行其他自定义逻辑
# 重定向回show页面
redirect_to admin_your_model_path(resource), notice: 'New record created successfully.'
end
end
上述代码中,我们使用action_item和collection_action或member_action方法来定义自定义操作。在custom_action的处理程序中,我们首先创建一个新的记录,然后保存它。然后,你可以在处理程序中执行任何其他自定义逻辑。最后,我们使用redirect_to重定向用户到适当的页面,并显示一个成功的提示消息。
确保将上述代码中的YourModel替换为你的模型名称,并根据需要进行其他修改。