Настройте метку активного администратора has_many
-
25-10-2019 - |
Вопрос
Ну, у меня есть две модели, связанные с домом.
#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, но ни один из этих вариантов не работает, я также пытался с: Легенда,: Название и: этикетка вместо: имя в .has_many. Не работает.
Это результат этого кода:Скриншот
Я хочу отобразить «версии документов» вместо «документов» и «добавить новую версию документа» вместо «добавить новый документ»
Если кто -то может иметь решение, это было бы здорово
Решение
Устанавливать has_many
Заголовок, который вы можете использовать
f.has_many :images, heading: 'My images' do |i|
i.input :src, label: false
end
Видеть здесь
Другие советы
Смотря на ActiveEadmin Tests(«должен перевести имя ассоциации в заголовке»), может быть другой способ сделать это. Используйте свой файл перевода.
Если вы посмотрите на ActiveEadmin Has_many Метод (yuck !!! 46 строки последовательного кода), он использует Человеческий метод ActiveModel.
Попробуйте добавить это в свой файл перевода
en:
activerecord:
models:
document:
one: Document Version
other: Document Versions
Один быстрый взлом - это то, что вы можете скрыть тег H3 через его стиль.
Assets/StyleShips/active_admin.css.scss
.has_many {
h3 {
display: none;
}}
Это скрывает любой тег H3 в классе has_many.
Ответ SJORS на самом деле является идеальным началом решения вопроса. I Monkecatatchated Active Admin в конфигурации/инициализаторах/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
Теперь в моем файле администратора я называю название nated_has_many, как has_many, но я передаю: заголовок, чтобы переопределить использование ассоциации в качестве тега H3.
f.titled_has_many :association, header: "Display this as the H3" do |app_f|
#stuff here
end
Вы можете настроить метку кнопки «Добавить ...», используя 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
Не заслуживает приза, но вы можете поместить это в config/initializers/active_admin.rb. Это позволит вам настроить желаемые заголовки, используя конфигурацию/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
Если у вас есть проблемы с локальными файлами, которые не загружаются в режиме постановки/производства, добавление этого в ваше приложение.
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