Настройте метку активного администратора has_many

Ну, у меня есть две модели, связанные с ассоциацией on-to-many.

#models/outline.rb
    class Outline < ActiveRecord::Base
      has_many :documents
    end

#models/document.rb
    class Document < ActiveRecord::Base
      belongs_to :outline
    end

#admin/outlines.rb
    ActiveAdmin.register Outline do
      form do |f|
        f.inputs "Details" do
          f.input :name, :required => true
          f.input :pages, :required => true
          ...
          f.buttons
        end
        f.inputs "Document Versions" do 
          f.has_many :documents, :name => "Document Versions"  do |d|
            d.input :file, :as => :file
            d.buttons do
              d.commit_button :title => "Add new Document Version"
            end
          end
        end
      end
    end

Что ж, как вы можете видеть в admin/outlines.rb, я уже пытался настроить :name, в has_many :documents и :title в commit_button, но ни один из этих вариантов не работает, я также пробовал с :legend, : title и :label вместо :name в файле .has_many. Не работает.

Вот результат этого кода: Снимок экрана

Я хочу отобразить «Версии документа» вместо «Документы» и «Добавить новую версию документа» вместо «Добавить новый документ».

Если у кого-то есть решение, было бы здорово


person MatisMasters    schedule 29.11.2011    source источник
comment
У меня такая же проблема, я написал в баг-трекере. Возможно, вы можете добавить к нему дополнительную информацию: github.com/gregbell/active_admin/issues/786   -  person bruno077    schedule 29.11.2011
comment
Кажется, нельзя: form_buffers.last << template.content_tag(:h3, association.to_s.titlecase) (от активного админа form_builder.rb)   -  person fro_oo    schedule 12.02.2012


Ответы (6)


Чтобы установить заголовок has_many, вы можете использовать

f.has_many :images, heading: 'My images' do |i|
  i.input :src, label: false
end

См. здесь

person timfjord    schedule 06.09.2013

Глядя на тесты ActiveAdmin("следует перевести имя ассоциации в заголовке"), может быть другой способ сделать это. Используйте свой файл перевода.

Если вы посмотрите на метод ActiveAdmin has_many (фу!! 46 строк последовательного кода), он использует ActiveModel человеческий метод.

Попробуйте добавить это в свой файл перевода

en:
  activerecord:
    models:
      document:
        one: Document Version
        other: Document Versions
person ReggieB    schedule 22.11.2012
comment
Это самый простой способ справиться с изменением имени класса в ваших формах. Примите все мои голоса. - person Josh Kovach; 27.03.2013
comment
Как это не лучший ответ? Это так так просто! Спасибо. - person Mike Doyle; 12.03.2014

Одним из быстрых способов является то, что вы можете скрыть тег h3 через его стиль.

активы/таблицы стилей/active_admin.css.scss

    .has_many {
      h3 {
        display: none;
      }}

Это скроет любой тег h3 в классе has_many.

person Billy Shambrook    schedule 08.03.2012

Вы можете настроить метку кнопки "Добавить...", используя настройку new_record на has_many. Для метки заголовка вы можете использовать heading:

f.has_many :documents,
           heading: "Document Versions",
           new_record: "Add new Document Version" do |d|
  d.input :file, :as => :file
end
person stigi    schedule 04.01.2018

Ответ Sjors на самом деле является идеальным началом для решения вопроса. Я пропатчил Active Admin в config/initializers/active_admin.rb следующим образом:

module ActiveAdmin
 class FormBuilder < ::Formtastic::FormBuilder
  def titled_has_many(association, options = {}, &block)
   options = { :for => association }.merge(options)
   options[:class] ||= ""
   options[:class] << "inputs has_many_fields"

   # Set the Header
   header = options[:header] || association.to_s

   # Add Delete Links
   form_block = proc do |has_many_form|
     block.call(has_many_form) + if has_many_form.object.new_record?
                                  template.content_tag :li do
                                    template.link_to I18n.t('active_admin.has_many_delete'), "#", :onclick => "$(this).closest('.has_many_fields').remove(); return false;", :class => "button"
                                  end
                                else
                                end
  end

  content = with_new_form_buffer do
    template.content_tag :div, :class => "has_many #{association}" do
      form_buffers.last << template.content_tag(:h3, header.titlecase) #using header
      inputs options, &form_block

      # Capture the ADD JS
      js = with_new_form_buffer do
        inputs_for_nested_attributes  :for => [association, object.class.reflect_on_association(association).klass.new],
                                      :class => "inputs has_many_fields",
                                      :for_options => {
                                        :child_index => "NEW_RECORD"
                                      }, &form_block
      end

      js = template.escape_javascript(js)
      js = template.link_to I18n.t('active_admin.has_many_new', :model => association.to_s.singularize.titlecase), "#", :onclick => "$(this).before('#{js}'.replace(/NEW_RECORD/g, new Date().getTime())); return false;", :class => "button"

      form_buffers.last << js.html_safe
    end
  end
  form_buffers.last << content.html_safe
  end
 end
end

Теперь в моем файле администратора я вызываю titled_has_many точно так же, как has_many, но я передаю :header, чтобы переопределить использование ассоциации в качестве тега h3.

f.titled_has_many :association, header: "Display this as the H3" do |app_f|
  #stuff here
end
person Sean Dixon    schedule 31.07.2012
comment
Спасибо приятель! Если у меня будет время, я попытаюсь применить это исправление к репозиторию active_admin. - person Szymon Przybył; 02.08.2012
comment
но здесь есть еще одна проблема - мы не можем переименовать кнопку «Добавить больше ресурсов» :/ - person Szymon Przybył; 02.08.2012

Не заслуживает приза, но вы можете поместить это в config/initializers/active_admin.rb. Это позволит вам настроить заголовки, которые вы хотите, используя config/locales/your_file.yml (вы должны сами создать запись custom_translations). Не забудьте перезапустить сервер. И используйте f.hacked_has_many в своем конструкторе форм.

module ActiveAdmin
  class FormBuilder < ::Formtastic::FormBuilder
    def hacked_has_many(association, options = {}, &block)
      options = { :for => association }.merge(options)
      options[:class] ||= ""
      options[:class] << "inputs has_many_fields"
      # Add Delete Links
      form_block = proc do |has_many_form|
        block.call(has_many_form) + if has_many_form.object.new_record?
                                      template.content_tag :li do
                                        template.link_to I18n.t('active_admin.has_many_delete'), "#", :onclick => "$(this).closest('.has_many_fields').remove(); return false;", :class => "button"
                                      end
                                    else
                                    end
      end
      content = with_new_form_buffer do
        template.content_tag :div, :class => "has_many #{association}" do         

          # form_buffers.last << template.content_tag(:h3, association.to_s.titlecase)
          # CHANGED INTO
          form_buffers.last << template.content_tag(:h3, I18n.t('custom_translations.'+association.to_s))

          inputs options, &form_block

          # Capture the ADD JS
          js = with_new_form_buffer do
            inputs_for_nested_attributes  :for => [association, object.class.reflect_on_association(association).klass.new],
                                          :class => "inputs has_many_fields",
                                          :for_options => {
                                            :child_index => "NEW_RECORD"
                                          }, &form_block
          end
          js = template.escape_javascript(js)
          _model = 'activerecord.models.' + association.to_s.singularize
          _translated_model = I18n.t(_model)
          js = template.link_to I18n.t('active_admin.has_many_new', :model => _translated_model), "#", :onclick => "$(this).before('#{js}'.replace(/NEW_RECORD/g, new Date().getTime())); return false;", :class => "button"

          form_buffers.last << js.html_safe
        end
      end
      form_buffers.last << content.html_safe
    end
  end
end

Если у вас есть проблемы с файлами локали, которые не загружаются должным образом в промежуточном/производственном режиме, может помочь добавление этого в ваш application.rb (замените :nl на правильную локаль)

config.before_configuration do
  I18n.load_path += Dir[Rails.root.join('config','locales','*.{rb,yml}').to_s]
  I18n.locale = :nl
  I18n.default_locale = :nl
  config.i18n.load_path += Dir[Rails.root.join('config','locales','*.{rb,yml}').to_s]
  config.i18n.locale = :nl
  config.i18n.default_locale = :nl
  I18n.reload!
  config.i18n.reload!
end
config.i18n.locale = :nl
config.i18n.default_locale = :nl 
person Sjors Branderhorst    schedule 19.04.2012