选择' has_many通过' Active Admin中的关联

时间:2015-01-14 00:59:37

标签: ruby-on-rails associations activeadmin has-many-through

我已经看到了几个同样问题的问题,例如。

Using HABTM or Has_many through with Active Admin

但我仍然在努力让事情发挥作用(此时我已尝试过多种方式)。

我的模型(稍微复杂于用户模型的'技术员'别名):

class AnalysisType < ActiveRecord::Base
  has_many :analysis_type_technicians, :dependent => :destroy
  has_many :technicians, :class_name => 'User', :through => :analysis_type_technicians
  accepts_nested_attributes_for :analysis_type_technicians, allow_destroy: true
end

class User < ActiveRecord::Base
  has_many :analysis_type_technicians, :foreign_key => 'technician_id', :dependent => :destroy
  has_many :analysis_types, :through => :analysis_type_technicians
end

class AnalysisTypeTechnician < ActiveRecord::Base
  belongs_to :analysis_type, :class_name => 'AnalysisType', :foreign_key => 'analysis_type_id' 
  belongs_to :technician, :class_name => 'User', :foreign_key => 'technician_id'
end

我已经为AnalysisType模型注册了一个ActiveAdmin模型,并且希望能够选择(已经创建)技术人员以在下拉列表/复选框中与该AnalysisType相关联。我的ActiveAdmin设置目前如下:

ActiveAdmin.register AnalysisType do
  form do |f|
    f.input :analysis_type_technicians, as: :check_boxes, :collection => User.all.map{ |tech|  [tech.surname, tech.id] }
    f.actions
  end 

  permit_params do
    permitted = [:name, :description, :instrumentID, analysis_type_technicians_attributes: [:technician_id] ]
    permitted
  end

end  

虽然表格似乎显示正常,但选定的技术人员在提交时并未附上。在日志中我收到错误'未经许可的参数:analysis_type_technician_ids'。

我已尝试过多种方式在其他相关的SO页面中执行此操作,但总是遇到同样的问题,即某些性质的未经许可的参数。谁能指出我做错了什么? (我顺便使用Rails 4)

1 个答案:

答案 0 :(得分:16)

通过has_and_belongs_to_manyhas_many关系管理关联 不需要使用accepts_nested_attributes_for。这种形式 输入正在管理与AnalysisType记录关联的技术人员ID。 如下所示,定义允许的参数和形式应该允许 那些要创建的协会。

ActiveAdmin.register AnalysisType do
  form do |f|
    f.input :technicians, as: :check_boxes, :collection => User.all.map{ |tech|  [tech.surname, tech.id] }
    f.actions
  end

  permit_params :name, :description, :instrumentID, :technician_ids => []
end

如果需要创建新的技术人员记录 何时使用accepts_nested_attributes_for


注意:更新了与评论匹配的答案。