Подтвердить что ты не робот

Настроить ярлык Active Admin has_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 Я уже пробовал настроить: имя в документах has_many: и заголовок в commit_button, но ни один из этих параметров не работает, я также попытался: legend,: title и: label, а не: name в .has_many. Не работает.

Это результат этого кода: Screenshot

То, что я хочу отобразить, это "Версии документов" вместо "Документы" и "Добавить новую версию документа" вместо "Добавить новый документ"

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

4b9b3361

Ответ 1

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

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

Смотрите здесь

Ответ 2

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

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

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

en:
  activerecord:
    models:
      document:
        one: Document Version
        other: Document Versions

Ответ 3

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

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

    .has_many {
      h3 {
        display: none;
      }}

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

Ответ 4

Ответ 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

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

f.titled_has_many :association, header: "Display this as the H3" do |app_f|
  #stuff here
end

Ответ 5

Не стоит выигрывать, но вы можете поместить его в 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

Если у вас есть проблемы с загрузкой файлов локали, которые не загружаются в режиме промежуточного/производственного процесса, добавление этого в ваше приложение .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 

Ответ 6

Вы можете настроить метку кнопки "Добавить...", используя параметр 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