如何使用ActiveAdmin创建STI子类的对象 [英] How to create an object of a STI subclass using ActiveAdmin

查看:58
本文介绍了如何使用ActiveAdmin创建STI子类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下设置(当前不起作用)

Given the following setup(which is not working currently)

class Employee < ActiveRecord::Base
end

class Manager < Employee
end

ActiveAdmin.register Employee do
  form do |f|
    f.input :name
    f.input :joining_date
    f.input :salary
    f.input :type, as: select, collection: Employee.descendants.map(&:name)
  end
end

我想要一个适用于所有员工的新表格,并能够在表格中选择该员工的STI类型。
我能够看到预期的类型选择框,但是当我按下创建按钮时,出现以下错误:

I would like to have a single "new" form for all employees and be able to select the STI type of the employee in the form. I am able to see the select box for "type" as intended but when I hit the "Create" button, I get the following error:

ActiveModel::MassAssignmentSecurity::Error in Admin::EmployeesController#create

Can't mass-assign protected attributes: type

现在,我知道受保护的属性在Rails中的工作方式,并且我有一些变通办法,例如定义 Employee。 attribute_protected_by_default ,但这会降低安全性,而且太容易被黑客攻击。

Now, I am aware of the way protected attributes work in Rails and I have a couple of workarounds such as defining Employee.attributes_protected_by_default but that is lowering the security and too hack-y.

我希望能够使用ActiveAdmin中的某些功能来做到这一点,但我找不到一个。我不想创建自定义控制器动作,因为我展示的示例已高度简化和人为设计。

I want to be able to do this using some feature in ActiveAdmin but I can't find one. I do not want to have to create a custom controller action as the example I showed is highly simplified and contrived.

我希望由ActiveAdmin生成的控制器可以识别 type 并执行 Manager.create 而不是 Employee.create

I wish that somehow the controller generated by ActiveAdmin would identify type and do Manager.create instead of Employee.create

有人知道解决方法吗?

推荐答案

您可以自定义控制器你自己阅读有关自定义控制器的ActiveAdmin文档。这是一个简单的示例:

You can customize the controller yourself. Read ActiveAdmin Doc on Customizing Controllers. Here is a quick example:

controller do
  alias_method :create_user, :create
  def create
    # do what you need to here
    # then call create_user alias
    # which calls the original create
    create_user
    # or do the create yourself and don't
    # call create_user
  end
end

这篇关于如何使用ActiveAdmin创建STI子类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆