Rails ActiveAdmin提交表单前设置关联表字段值的问题
嘿,我来帮你解决这个ActiveAdmin里关联模型属性设置的问题!你遇到的“no implicit conversion from Symbol to Integer”错误,大概率是因为没处理好has_many关联对应的属性数组——毕竟table2_attributes是一个数组(对应多个Table2实例),直接用符号索引肯定会报错。下面给你两种可行的解决方案:
解决方法
方法一:在控制器中处理(推荐)
既然你已经在app/admin/table1.rb里自定义了create和update方法,那只需要在调用super前,遍历table2_attributes数组,给每个子项的attribute3设为true就行。代码示例如下:
# app/admin/table1.rb ActiveAdmin.register Table1 do permit_params :table1_attribute1, :table1_attribute2, table2_attributes: Table2::ATTRIBUTES controller do def create # 处理Table2的attribute3 if params[:table1][:table2_attributes].present? params[:table1][:table2_attributes].each do |_key, t2_attrs| t2_attrs[:attribute3] = true end end super end def update # 同样的逻辑处理update场景 if params[:table1][:table2_attributes].present? params[:table1][:table2_attributes].each do |_key, t2_attrs| t2_attrs[:attribute3] = true end end super end end end
为什么这样能行?
has_many关联的*_attributes参数是一个哈希数组(键通常是索引或id,值是对应子模型的属性哈希),所以我们需要遍历每个子属性哈希,手动设置attribute3为true,再交给ActiveAdmin的默认逻辑处理。
方法二:在视图中通过隐藏字段设置
如果你更倾向于在表单层面处理,可以在Table2的嵌套表单里添加隐藏字段,强制把attribute3设为true。代码示例:
# app/admin/table1.rb ActiveAdmin.register Table1 do permit_params :table1_attribute1, :table1_attribute2, table2_attributes: Table2::ATTRIBUTES + [:attribute3] form do |f| f.inputs 'Table1 Info' do f.input :table1_attribute1 f.input :table1_attribute2 end f.inputs 'Table2 Entries' do f.has_many :table2, allow_destroy: true do |t2_f| t2_f.input :attribute1 t2_f.input :attribute2 # 添加隐藏字段,固定attribute3为true t2_f.input :attribute3, as: :hidden, input_html: { value: true } end end f.actions end end
注意点:
- 要确保
permit_params里包含:attribute3(如果Table2::ATTRIBUTES里没包含的话),不然参数会被过滤掉。 - 这个方法会在表单渲染时就把
attribute3的值固定为true,用户无法修改(因为是隐藏字段),适合不需要用户干预的场景。
内容的提问来源于stack exchange,提问作者nanakondor
相关产品推荐
相关产品推荐

