option_groups_from_collection_for_select超过两个级别

时间:2018-01-26 11:10:06

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

我的模型中有四个级别的_has_many_,我想在ActiveAdmin输入中执行它。

我的模特

class IsicSeccion < ActiveRecord::Base
   has_many :isicDivisiones
end

class IsicDivision < ActiveRecord::Base
  belongs_to :isic_seccion
  has_many :isicGrupos
end

class IsicGrupo < ActiveRecord::Base
  belongs_to :isic_division
  has_many :isicclases
end

class Isicclase < ActiveRecord::Base
  belongs_to :isic_grupo
end

class Configuracion < ActiveRecord::Base

    translates :comercial, :polcorreo, :personal, :bienvenida, :galleta, :aviso_galleta, :privacidad, :aviso_legal, :proteccion_de_datos, :slogan1, :slogan2

   has_many :configuracion_isicclases
.....
end

有效管理员注册

ActiveAdmin.register Configuracion do

 permit_params :comercial, :social, :polcorreo, :personal, :bienvenida, :localizacion, :galleta, :slogan1, :slogan2, :logo, :logo_file_name, :privacidad, :aviso_legal, :locale, :proteccion_de_datos, isicclase_ids: [] 
   form do |f|
      f.actions
       f.semantic_errors *f.object.errors.keys
      f.inputs "Configuración" do
         tabs do
            tab 'Empresa' do

                  #f.input :isicclases, as: :select, multiple: true, label: 'Código ISIC', :collection => Isicclase.all.map{|x|[x.codigo + "-" + x.titulo,x.id]}, include_blank: false 
                  f.input :isicclases, as: :select, multiple: true, label: 'Código ISIC', :collection => option_groups_from_collection_for_select(IsicGrupo.all, :isicclases, :titulo, :id, :titulo) , include_blank: false 

........

end

现在我使用的是option_groups_from_collection_for_select,但只能在两个级别中使用。

我正在考虑在 configuracion 模型中创建一个方法来创建一个自定义选择标记组,其中包含所有级别。

1 个答案:

答案 0 :(得分:0)

最后我决定在我的模型中创建一个方法。这个方法将重新启动我需要完成ActiveAdmin寄存器集合的输入。

在activeAdmin注册表中

f.input :isicclases, as: :select, multiple: true, label: 'Código ISIC', :collection => Configuracion.first.isic_collection_for_select, include_blank: false

在Configuracion模型中

  def isic_collection_for_select 
      vuelta = ""
      IsicSeccion.all.each do |sec|
         vuelta << "<optgroup label=\"#{sec.codigo + "-" + sec.titulo}\">"
         sec.isicDivisiones.each do |div|
            vuelta << "<optgroup label=\"&nbsp;#{div.codigo + "--"  + div.titulo}\">"
            div.isicGrupos.each do |grp|
               vuelta << "<optgroup label=\"&nbsp;&nbsp;#{grp.codigo + "--" +  grp.titulo}\">"
               grp.isicclases.each do |cls|
                  vuelta << "<option value=\"#{cls.id}\">#{cls.codigo + " " + cls.titulo}</option>\n"
               end
            end
            vuelta << "</optgroup>"
         end
         vuelta << "</optgroup>"
      end
      vuelta << "</optgroup>"

      vuelta.html_safe
   end