Home > Blockchain >  how to limit "Add new" to accept only X number of nested objects in active admin ruby on r
how to limit "Add new" to accept only X number of nested objects in active admin ruby on r

Time:06-03

I have Questions those have has_many association with possible_answers. The nested form that opens on "add new possible answers" are unlimited. i want to limit it to 5 which means user can click on this button for maximum 5 times after that it should disappear.

javascript seems to be a solution for this but i'm not good with it. how can i do it please guide.

form do |f|
  f.inputs do
    f.input :title, label: 'Question Title'
    f.inputs do
      f.has_many :possible_answers do |pa|
        pa.input :content
        pa.input :correct
      end
    end
  end
 f.actions
end

CodePudding user response:

In active_admin.js you can write this code. Or you can write it in "name.js" file and require it in active_admin.js i.e: //=require name . here is the code:

function toggleAddButton() {
  if ($('.has_many_fields').length == 5) {
    $('.has_many_add').hide()
  }
}

document.addEventListener("turbolinks:load", function() {
  $('.has_many_add').on("click",function() {
    setTimeout(() => {
      toggleAddButton();

      $('.has_many_remove').each(function(_ , element) {
        element.addEventListener('click', function() {
          $('.has_many_add').show()
        })
      })
    }, 200);
  })
})

the classes .has_many_add and .has_many_remove can be seen by inspecting element on browser.

  • Related